From 06b49e3e7dd4d66a4eb698987fad8f82c555a1cb Mon Sep 17 00:00:00 2001 From: sigonasr2 Date: Mon, 15 Aug 2022 22:04:55 -0500 Subject: [PATCH] Include project setup for running on a local system --- index.js | 2 + node_modules/.package-lock.json | 218 + .../@socket.io/component-emitter/LICENSE | 24 + .../@socket.io/component-emitter/Readme.md | 74 + .../@socket.io/component-emitter/index.d.ts | 179 + .../@socket.io/component-emitter/index.js | 176 + .../@socket.io/component-emitter/index.mjs | 169 + .../@socket.io/component-emitter/package.json | 31 + node_modules/@types/node/LICENSE | 21 + node_modules/@types/node/README.md | 16 + node_modules/@types/node/assert.d.ts | 911 ++++ node_modules/@types/node/assert/strict.d.ts | 8 + node_modules/@types/node/async_hooks.d.ts | 501 ++ node_modules/@types/node/buffer.d.ts | 2238 +++++++++ node_modules/@types/node/child_process.d.ts | 1369 +++++ node_modules/@types/node/cluster.d.ts | 410 ++ node_modules/@types/node/console.d.ts | 412 ++ node_modules/@types/node/constants.d.ts | 18 + node_modules/@types/node/crypto.d.ts | 3964 +++++++++++++++ node_modules/@types/node/dgram.d.ts | 545 ++ .../@types/node/diagnostics_channel.d.ts | 153 + node_modules/@types/node/dns.d.ts | 659 +++ node_modules/@types/node/dns/promises.d.ts | 370 ++ node_modules/@types/node/domain.d.ts | 170 + node_modules/@types/node/events.d.ts | 641 +++ node_modules/@types/node/fs.d.ts | 3872 ++++++++++++++ node_modules/@types/node/fs/promises.d.ts | 1120 +++++ node_modules/@types/node/globals.d.ts | 294 ++ node_modules/@types/node/globals.global.d.ts | 1 + node_modules/@types/node/http.d.ts | 1452 ++++++ node_modules/@types/node/http2.d.ts | 2106 ++++++++ node_modules/@types/node/https.d.ts | 401 ++ node_modules/@types/node/index.d.ts | 132 + node_modules/@types/node/inspector.d.ts | 2741 ++++++++++ node_modules/@types/node/module.d.ts | 114 + node_modules/@types/node/net.d.ts | 816 +++ node_modules/@types/node/os.d.ts | 456 ++ node_modules/@types/node/package.json | 225 + node_modules/@types/node/path.d.ts | 191 + node_modules/@types/node/perf_hooks.d.ts | 610 +++ node_modules/@types/node/process.d.ts | 1482 ++++++ node_modules/@types/node/punycode.d.ts | 117 + node_modules/@types/node/querystring.d.ts | 131 + node_modules/@types/node/readline.d.ts | 653 +++ .../@types/node/readline/promises.d.ts | 143 + node_modules/@types/node/repl.d.ts | 424 ++ node_modules/@types/node/stream.d.ts | 1339 +++++ .../@types/node/stream/consumers.d.ts | 24 + node_modules/@types/node/stream/promises.d.ts | 42 + node_modules/@types/node/stream/web.d.ts | 330 ++ node_modules/@types/node/string_decoder.d.ts | 67 + node_modules/@types/node/test.d.ts | 176 + node_modules/@types/node/timers.d.ts | 94 + node_modules/@types/node/timers/promises.d.ts | 68 + node_modules/@types/node/tls.d.ts | 1028 ++++ node_modules/@types/node/trace_events.d.ts | 171 + node_modules/@types/node/tty.d.ts | 206 + node_modules/@types/node/url.d.ts | 897 ++++ node_modules/@types/node/util.d.ts | 1792 +++++++ node_modules/@types/node/v8.d.ts | 396 ++ node_modules/@types/node/vm.d.ts | 509 ++ node_modules/@types/node/wasi.d.ts | 158 + node_modules/@types/node/worker_threads.d.ts | 646 +++ node_modules/@types/node/zlib.d.ts | 517 ++ node_modules/data-uri-to-buffer/README.md | 88 + .../data-uri-to-buffer/dist/index.d.ts | 15 + node_modules/data-uri-to-buffer/dist/index.js | 53 + .../data-uri-to-buffer/dist/index.js.map | 1 + .../data-uri-to-buffer/dist/src/index.d.ts | 15 + .../data-uri-to-buffer/dist/src/index.js | 53 + .../data-uri-to-buffer/dist/src/index.js.map | 1 + .../data-uri-to-buffer/dist/test/test.d.ts | 4 + .../data-uri-to-buffer/dist/test/test.js | 144 + .../data-uri-to-buffer/dist/test/test.js.map | 1 + node_modules/data-uri-to-buffer/package.json | 62 + node_modules/data-uri-to-buffer/src/index.ts | 68 + node_modules/debug/LICENSE | 20 + node_modules/debug/README.md | 481 ++ node_modules/debug/package.json | 59 + node_modules/debug/src/browser.js | 269 + node_modules/debug/src/common.js | 274 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/node.js | 263 + node_modules/dotenv/CHANGELOG.md | 356 ++ node_modules/dotenv/LICENSE | 23 + node_modules/dotenv/README.md | 408 ++ node_modules/dotenv/config.d.ts | 1 + node_modules/dotenv/config.js | 9 + node_modules/dotenv/lib/cli-options.js | 11 + node_modules/dotenv/lib/env-options.js | 20 + node_modules/dotenv/lib/main.d.ts | 73 + node_modules/dotenv/lib/main.js | 109 + node_modules/dotenv/package.json | 56 + node_modules/engine.io-client/LICENSE | 22 + node_modules/engine.io-client/README.md | 333 ++ .../build/cjs/browser-entrypoint.js | 4 + .../build/cjs/contrib/has-cors.js | 14 + .../build/cjs/contrib/parseqs.js | 39 + .../build/cjs/contrib/parseuri.js | 53 + .../build/cjs/contrib/yeast.js | 55 + .../build/cjs/globalThis.browser.js | 14 + .../engine.io-client/build/cjs/globalThis.js | 4 + .../engine.io-client/build/cjs/index.js | 14 + .../engine.io-client/build/cjs/package.json | 10 + .../engine.io-client/build/cjs/socket.js | 611 +++ .../engine.io-client/build/cjs/transport.js | 126 + .../build/cjs/transports/index.js | 9 + .../build/cjs/transports/polling.js | 427 ++ .../websocket-constructor.browser.js | 16 + .../cjs/transports/websocket-constructor.js | 11 + .../build/cjs/transports/websocket.js | 198 + .../cjs/transports/xmlhttprequest.browser.js | 23 + .../build/cjs/transports/xmlhttprequest.js | 28 + .../engine.io-client/build/cjs/util.js | 58 + .../build/esm-debug/browser-entrypoint.d.ts | 3 + .../build/esm-debug/browser-entrypoint.js | 2 + .../build/esm-debug/contrib/has-cors.d.ts | 1 + .../build/esm-debug/contrib/has-cors.js | 11 + .../build/esm-debug/contrib/parseqs.d.ts | 15 + .../build/esm-debug/contrib/parseqs.js | 34 + .../build/esm-debug/contrib/parseuri.d.ts | 1 + .../build/esm-debug/contrib/parseuri.js | 49 + .../build/esm-debug/contrib/yeast.d.ts | 23 + .../build/esm-debug/contrib/yeast.js | 50 + .../build/esm-debug/globalThis.browser.d.ts | 1 + .../build/esm-debug/globalThis.browser.js | 11 + .../build/esm-debug/globalThis.d.ts | 1 + .../build/esm-debug/globalThis.js | 1 + .../build/esm-debug/index.d.ts | 8 + .../engine.io-client/build/esm-debug/index.js | 7 + .../build/esm-debug/package.json | 10 + .../build/esm-debug/socket.d.ts | 352 ++ .../build/esm-debug/socket.js | 604 +++ .../build/esm-debug/transport.d.ts | 96 + .../build/esm-debug/transport.js | 119 + .../build/esm-debug/transports/index.d.ts | 6 + .../build/esm-debug/transports/index.js | 6 + .../build/esm-debug/transports/polling.d.ts | 142 + .../build/esm-debug/transports/polling.js | 419 ++ .../websocket-constructor.browser.d.ts | 4 + .../websocket-constructor.browser.js | 13 + .../transports/websocket-constructor.d.ts | 4 + .../transports/websocket-constructor.js | 5 + .../build/esm-debug/transports/websocket.d.ts | 55 + .../build/esm-debug/transports/websocket.js | 191 + .../transports/xmlhttprequest.browser.d.ts | 1 + .../transports/xmlhttprequest.browser.js | 19 + .../esm-debug/transports/xmlhttprequest.d.ts | 1 + .../esm-debug/transports/xmlhttprequest.js | 2 + .../build/esm-debug/util.d.ts | 3 + .../engine.io-client/build/esm-debug/util.js | 52 + .../build/esm/browser-entrypoint.d.ts | 3 + .../build/esm/browser-entrypoint.js | 2 + .../build/esm/contrib/has-cors.d.ts | 1 + .../build/esm/contrib/has-cors.js | 11 + .../build/esm/contrib/parseqs.d.ts | 15 + .../build/esm/contrib/parseqs.js | 34 + .../build/esm/contrib/parseuri.d.ts | 1 + .../build/esm/contrib/parseuri.js | 49 + .../build/esm/contrib/yeast.d.ts | 23 + .../build/esm/contrib/yeast.js | 50 + .../build/esm/globalThis.browser.d.ts | 1 + .../build/esm/globalThis.browser.js | 11 + .../build/esm/globalThis.d.ts | 1 + .../engine.io-client/build/esm/globalThis.js | 1 + .../engine.io-client/build/esm/index.d.ts | 8 + .../engine.io-client/build/esm/index.js | 7 + .../engine.io-client/build/esm/package.json | 10 + .../engine.io-client/build/esm/socket.d.ts | 352 ++ .../engine.io-client/build/esm/socket.js | 579 +++ .../engine.io-client/build/esm/transport.d.ts | 96 + .../engine.io-client/build/esm/transport.js | 116 + .../build/esm/transports/index.d.ts | 6 + .../build/esm/transports/index.js | 6 + .../build/esm/transports/polling.d.ts | 142 + .../build/esm/transports/polling.js | 403 ++ .../websocket-constructor.browser.d.ts | 4 + .../websocket-constructor.browser.js | 13 + .../esm/transports/websocket-constructor.d.ts | 4 + .../esm/transports/websocket-constructor.js | 5 + .../build/esm/transports/websocket.d.ts | 55 + .../build/esm/transports/websocket.js | 188 + .../transports/xmlhttprequest.browser.d.ts | 1 + .../esm/transports/xmlhttprequest.browser.js | 19 + .../build/esm/transports/xmlhttprequest.d.ts | 1 + .../build/esm/transports/xmlhttprequest.js | 2 + .../engine.io-client/build/esm/util.d.ts | 3 + .../engine.io-client/build/esm/util.js | 52 + .../dist/engine.io.esm.min.js | 7 + .../dist/engine.io.esm.min.js.map | 1 + .../engine.io-client/dist/engine.io.js | 2435 +++++++++ .../engine.io-client/dist/engine.io.js.map | 1 + .../engine.io-client/dist/engine.io.min.js | 7 + .../dist/engine.io.min.js.map | 1 + node_modules/engine.io-client/package.json | 104 + node_modules/engine.io-parser/LICENSE | 22 + node_modules/engine.io-parser/Readme.md | 158 + .../engine.io-parser/build/cjs/commons.js | 19 + .../build/cjs/contrib/base64-arraybuffer.js | 47 + .../build/cjs/decodePacket.browser.js | 51 + .../build/cjs/decodePacket.js | 49 + .../build/cjs/encodePacket.browser.js | 43 + .../build/cjs/encodePacket.js | 27 + .../engine.io-parser/build/cjs/index.js | 38 + .../engine.io-parser/build/cjs/package.json | 8 + .../engine.io-parser/build/esm/commons.d.ts | 14 + .../engine.io-parser/build/esm/commons.js | 14 + .../build/esm/contrib/base64-arraybuffer.d.ts | 2 + .../build/esm/contrib/base64-arraybuffer.js | 42 + .../build/esm/decodePacket.browser.d.ts | 3 + .../build/esm/decodePacket.browser.js | 49 + .../build/esm/decodePacket.d.ts | 3 + .../build/esm/decodePacket.js | 47 + .../build/esm/encodePacket.browser.d.ts | 3 + .../build/esm/encodePacket.browser.js | 41 + .../build/esm/encodePacket.d.ts | 3 + .../build/esm/encodePacket.js | 25 + .../engine.io-parser/build/esm/index.d.ts | 7 + .../engine.io-parser/build/esm/index.js | 32 + .../engine.io-parser/build/esm/package.json | 8 + node_modules/engine.io-parser/package.json | 58 + node_modules/fetch-blob/LICENSE | 21 + node_modules/fetch-blob/README.md | 106 + node_modules/fetch-blob/file.d.ts | 2 + node_modules/fetch-blob/file.js | 49 + node_modules/fetch-blob/from.d.ts | 26 + node_modules/fetch-blob/from.js | 100 + node_modules/fetch-blob/index.d.ts | 3 + node_modules/fetch-blob/index.js | 250 + node_modules/fetch-blob/package.json | 56 + node_modules/fetch-blob/streams.cjs | 51 + node_modules/formdata-polyfill/FormData.js | 441 ++ node_modules/formdata-polyfill/LICENSE | 21 + node_modules/formdata-polyfill/README.md | 145 + node_modules/formdata-polyfill/esm.min.d.ts | 5 + node_modules/formdata-polyfill/esm.min.js | 40 + .../formdata-polyfill/formdata-to-blob.js | 39 + .../formdata-polyfill/formdata.min.js | 21 + node_modules/formdata-polyfill/package.json | 50 + node_modules/heap/.npmignore | 2 + node_modules/heap/.travis.yml | 4 + node_modules/heap/Makefile | 17 + node_modules/heap/README.md | 211 + node_modules/heap/bower.json | 19 + node_modules/heap/index.js | 1 + node_modules/heap/lib/heap.js | 369 ++ node_modules/heap/package.json | 26 + node_modules/heap/src/heap.coffee | 213 + node_modules/heap/test/heap.test.coffee | 100 + node_modules/ms/index.js | 162 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 37 + node_modules/ms/readme.md | 60 + .../.history/README_20210527203617.md | 2 + .../.history/README_20210527212714.md | 41 + .../.history/README_20210527213345.md | 36 + .../.history/README_20210527213411.md | 36 + .../.history/README_20210527213803.md | 36 + .../.history/README_20210527214323.md | 38 + .../.history/README_20210527214408.md | 38 + .../.history/index_20210527203842.js | 0 .../.history/index_20210527203947.js | 8 + .../.history/index_20210527204259.js | 9 + .../.history/index_20210527204418.js | 9 + .../.history/index_20210527204756.js | 11 + .../.history/index_20210527204833.js | 11 + .../.history/index_20210527211208.js | 15 + .../.history/index_20210527211248.js | 15 + .../.history/index_20210527212722.js | 23 + .../.history/index_20210527212731.js | 23 + .../.history/index_20210527212746.js | 15 + .../.history/index_20210527212900.js | 16 + .../.history/index_20210527213022.js | 16 + .../.history/index_20210527213822.js | 16 + .../.history/index_20210527213843.js | 17 + .../.history/index_20210527213852.js | 17 + .../.history/index_20210527213910.js | 16 + .../.history/index_20210527214034.js | 16 + .../.history/index_20210527214643.js | 41 + .../.history/index_20210527214654.js | 41 + .../.history/index_20210527214700.js | 16 + .../.history/package_20210527203733.json | 19 + .../.history/package_20210527203825.json | 16 + .../.history/package_20210527204621.json | 19 + .../.history/package_20210527204913.json | 25 + .../.history/package_20210527204925.json | 25 + .../.history/package_20210527205145.json | 29 + .../.history/package_20210527205156.json | 29 + .../.history/test_20210527205603.js | 0 .../.history/test_20210527205957.js | 3 + .../.history/test_20210527210021.js | 3 + node_modules/node-domexception/LICENSE | 21 + node_modules/node-domexception/README.md | 46 + node_modules/node-domexception/index.js | 16 + node_modules/node-domexception/package.json | 29 + node_modules/node-fetch/@types/index.d.ts | 218 + node_modules/node-fetch/LICENSE.md | 22 + node_modules/node-fetch/README.md | 871 ++++ node_modules/node-fetch/package.json | 131 + node_modules/node-fetch/src/body.js | 397 ++ .../node-fetch/src/errors/abort-error.js | 10 + node_modules/node-fetch/src/errors/base.js | 17 + .../node-fetch/src/errors/fetch-error.js | 26 + node_modules/node-fetch/src/headers.js | 267 + node_modules/node-fetch/src/index.js | 417 ++ node_modules/node-fetch/src/request.js | 317 ++ node_modules/node-fetch/src/response.js | 141 + .../node-fetch/src/utils/get-search.js | 9 + .../node-fetch/src/utils/is-redirect.js | 11 + node_modules/node-fetch/src/utils/is.js | 87 + .../node-fetch/src/utils/multipart-parser.js | 432 ++ node_modules/node-fetch/src/utils/referrer.js | 340 ++ node_modules/pathfinding/.npmignore | 5 + node_modules/pathfinding/.travis.yml | 8 + node_modules/pathfinding/README.md | 264 + node_modules/pathfinding/TODO | 4 + .../pathfinding/benchmark/benchmark.js | 76 + .../pathfinding/benchmark/map/64room_000.map | 516 ++ .../pathfinding/benchmark/map/arena.map | 53 + .../pathfinding/benchmark/map/lak304d.map | 198 + .../pathfinding/benchmark/map/losttemple.map | 516 ++ .../pathfinding/benchmark/parse_map.js | 79 + .../pathfinding/benchmark/parse_scen.js | 48 + .../benchmark/scen/64room_000.map.scen | 2031 ++++++++ .../pathfinding/benchmark/scen/arena.map.scen | 161 + .../benchmark/scen/lak304d.map.scen | 774 +++ .../benchmark/scen/losttemple.map.scen | 1239 +++++ .../pathfinding/benchmark/test_cases.js | 11 + .../docs/contributor-guide/authors.md | 22 + .../docs/contributor-guide/contributing.md | 4 + .../docs/contributor-guide/developing.md | 0 node_modules/pathfinding/docs/custom.css | 18 + node_modules/pathfinding/docs/index.md | 15 + .../docs/user-guide/diagonal-movement.md | 52 + .../pathfinding/docs/user-guide/faq.md | 0 .../docs/user-guide/getting-started.md | 52 + .../docs/user-guide/images/5x7EmptyGrid.png | Bin 0 -> 1214 bytes .../images/5x7GridWithObstacles.png | Bin 0 -> 1282 bytes .../images/5x7GridWithObstaclesAndPath.png | Bin 0 -> 3143 bytes .../user-guide/images/5x7GridWithPath.png | Bin 0 -> 2524 bytes .../user-guide/images/AllMapsWithAPath.png | Bin 0 -> 2423 bytes .../images/AllMapsWithStraightPaths.png | Bin 0 -> 2070 bytes .../docs/user-guide/images/DiagonalMaps.png | Bin 0 -> 1683 bytes .../images/DiagonalMovementDisabled.png | Bin 0 -> 2017 bytes .../DiagonalPathsForAtMostOneObstacle.png | Bin 0 -> 2409 bytes .../DiagonalPathsForOnlyWhenNoObstacles.png | Bin 0 -> 2594 bytes .../docs/user-guide/images/images.svg | 2536 ++++++++++ .../docs/user-guide/installation.md | 109 + .../docs/user-guide/introduction.md | 51 + .../pathfinding/docs/user-guide/obstacles.md | 44 + node_modules/pathfinding/gulpfile.js | 102 + node_modules/pathfinding/index.js | 1 + node_modules/pathfinding/mkdocs.yml | 18 + node_modules/pathfinding/package.json | 1 + node_modules/pathfinding/src/PathFinding.js | 18 + node_modules/pathfinding/src/banner | 9 + .../pathfinding/src/core/DiagonalMovement.js | 8 + node_modules/pathfinding/src/core/Grid.js | 245 + .../pathfinding/src/core/Heuristic.js | 48 + node_modules/pathfinding/src/core/Node.js | 28 + node_modules/pathfinding/src/core/Util.js | 246 + .../pathfinding/src/finders/AStarFinder.js | 126 + .../src/finders/BestFirstFinder.js | 28 + .../pathfinding/src/finders/BiAStarFinder.js | 181 + .../src/finders/BiBestFirstFinder.js | 28 + .../src/finders/BiBreadthFirstFinder.js | 115 + .../src/finders/BiDijkstraFinder.js | 24 + .../src/finders/BreadthFirstFinder.js | 79 + .../pathfinding/src/finders/DijkstraFinder.js | 24 + .../pathfinding/src/finders/IDAStarFinder.js | 209 + .../src/finders/JPFAlwaysMoveDiagonally.js | 149 + .../JPFMoveDiagonallyIfAtMostOneObstacle.js | 155 + .../finders/JPFMoveDiagonallyIfNoObstacles.js | 174 + .../src/finders/JPFNeverMoveDiagonally.js | 120 + .../src/finders/JumpPointFinder.js | 31 + .../src/finders/JumpPointFinderBase.js | 114 + node_modules/pathfinding/test/Grid.js | 155 + node_modules/pathfinding/test/PathTest.js | 112 + .../pathfinding/test/PathTestScenarios.js | 64 + node_modules/pathfinding/test/Util.js | 52 + node_modules/pathfinding/visual/Makefile | 5 + node_modules/pathfinding/visual/css/style.css | 143 + .../visual/doc/state-description.md | 30 + .../pathfinding/visual/doc/state-diagram.gv | 19 + .../pathfinding/visual/doc/state-diagram.png | Bin 0 -> 49802 bytes node_modules/pathfinding/visual/index.html | 235 + .../pathfinding/visual/js/controller.js | 507 ++ node_modules/pathfinding/visual/js/main.js | 14 + node_modules/pathfinding/visual/js/panel.js | 184 + node_modules/pathfinding/visual/js/view.js | 335 ++ .../pathfinding/visual/lib/async.min.js | 1 + .../pathfinding/visual/lib/es5-shim.min.js | 16 + .../visual/lib/jquery-1.7.2.min.js | 4 + .../visual/lib/pathfinding-browser.min.js | 1 + .../pathfinding/visual/lib/raphael-min.js | 10 + .../visual/lib/state-machine.min.js | 1 + .../images/ui-bg_flat_0_aaaaaa_40x100.png | Bin 0 -> 180 bytes .../images/ui-bg_glass_95_fef1ec_1x400.png | Bin 0 -> 119 bytes .../ui-bg_gloss-wave_16_121212_500x100.png | Bin 0 -> 1968 bytes .../ui-bg_highlight-hard_15_888888_1x100.png | Bin 0 -> 95 bytes .../ui-bg_highlight-hard_55_555555_1x100.png | Bin 0 -> 115 bytes .../ui-bg_highlight-soft_35_adadad_1x100.png | Bin 0 -> 145 bytes .../ui-bg_highlight-soft_60_dddddd_1x100.png | Bin 0 -> 106 bytes .../ui-bg_inset-soft_15_121212_1x100.png | Bin 0 -> 103 bytes .../themes/images/ui-icons_666666_256x240.png | Bin 0 -> 4369 bytes .../themes/images/ui-icons_aaaaaa_256x240.png | Bin 0 -> 4369 bytes .../themes/images/ui-icons_bbbbbb_256x240.png | Bin 0 -> 5355 bytes .../themes/images/ui-icons_c98000_256x240.png | Bin 0 -> 5355 bytes .../themes/images/ui-icons_cccccc_256x240.png | Bin 0 -> 4369 bytes .../themes/images/ui-icons_cd0a0a_256x240.png | Bin 0 -> 4369 bytes .../themes/images/ui-icons_f29a00_256x240.png | Bin 0 -> 4369 bytes .../visual/lib/themes/jquery.ui.accordion.css | 19 + .../visual/lib/themes/jquery.ui.all.css | 11 + .../lib/themes/jquery.ui.autocomplete.css | 53 + .../visual/lib/themes/jquery.ui.base.css | 11 + .../visual/lib/themes/jquery.ui.button.css | 38 + .../visual/lib/themes/jquery.ui.core.css | 41 + .../lib/themes/jquery.ui.datepicker.css | 68 + .../visual/lib/themes/jquery.ui.dialog.css | 21 + .../lib/themes/jquery.ui.progressbar.css | 11 + .../visual/lib/themes/jquery.ui.resizable.css | 20 + .../lib/themes/jquery.ui.selectable.css | 10 + .../visual/lib/themes/jquery.ui.slider.css | 24 + .../visual/lib/themes/jquery.ui.tabs.css | 18 + .../visual/lib/themes/jquery.ui.theme.css | 249 + .../visual/lib/ui/jquery.ui.accordion.min.js | 30 + .../visual/lib/ui/jquery.ui.core.min.js | 18 + .../visual/lib/ui/jquery.ui.draggable.min.js | 50 + .../visual/lib/ui/jquery.ui.mouse.min.js | 17 + .../visual/lib/ui/jquery.ui.slider.min.js | 33 + .../visual/lib/ui/jquery.ui.widget.min.js | 15 + .../pathfinding/visual/notsupported.html | 28 + node_modules/socket.io-client/LICENSE | 22 + node_modules/socket.io-client/README.md | 29 + .../build/cjs/browser-entrypoint.js | 4 + .../build/cjs/contrib/backo2.js | 70 + .../socket.io-client/build/cjs/index.js | 69 + .../socket.io-client/build/cjs/manager.js | 395 ++ node_modules/socket.io-client/build/cjs/on.js | 10 + .../socket.io-client/build/cjs/socket.js | 616 +++ .../socket.io-client/build/cjs/url.js | 70 + .../build/esm-debug/browser-entrypoint.d.ts | 2 + .../build/esm-debug/browser-entrypoint.js | 2 + .../build/esm-debug/contrib/backo2.d.ts | 12 + .../build/esm-debug/contrib/backo2.js | 66 + .../build/esm-debug/index.d.ts | 29 + .../socket.io-client/build/esm-debug/index.js | 61 + .../build/esm-debug/manager.d.ts | 290 ++ .../build/esm-debug/manager.js | 369 ++ .../socket.io-client/build/esm-debug/on.d.ts | 2 + .../socket.io-client/build/esm-debug/on.js | 6 + .../build/esm-debug/package.json | 5 + .../build/esm-debug/socket.d.ts | 318 ++ .../build/esm-debug/socket.js | 609 +++ .../socket.io-client/build/esm-debug/url.d.ts | 33 + .../socket.io-client/build/esm-debug/url.js | 63 + .../build/esm/browser-entrypoint.d.ts | 2 + .../build/esm/browser-entrypoint.js | 2 + .../build/esm/contrib/backo2.d.ts | 12 + .../build/esm/contrib/backo2.js | 66 + .../socket.io-client/build/esm/index.d.ts | 29 + .../socket.io-client/build/esm/index.js | 57 + .../socket.io-client/build/esm/manager.d.ts | 290 ++ .../socket.io-client/build/esm/manager.js | 350 ++ .../socket.io-client/build/esm/on.d.ts | 2 + node_modules/socket.io-client/build/esm/on.js | 6 + .../socket.io-client/build/esm/package.json | 5 + .../socket.io-client/build/esm/socket.d.ts | 318 ++ .../socket.io-client/build/esm/socket.js | 593 +++ .../socket.io-client/build/esm/url.d.ts | 33 + .../socket.io-client/build/esm/url.js | 59 + .../dist/socket.io.esm.min.js | 7 + .../dist/socket.io.esm.min.js.map | 1 + .../socket.io-client/dist/socket.io.js | 4440 +++++++++++++++++ .../socket.io-client/dist/socket.io.js.map | 1 + .../socket.io-client/dist/socket.io.min.js | 7 + .../dist/socket.io.min.js.map | 1 + .../dist/socket.io.msgpack.min.js | 7 + .../dist/socket.io.msgpack.min.js.map | 1 + node_modules/socket.io-client/package.json | 122 + node_modules/socket.io-parser/LICENSE | 20 + node_modules/socket.io-parser/Readme.md | 81 + .../socket.io-parser/build/cjs/binary.js | 88 + .../socket.io-parser/build/cjs/index.js | 298 ++ .../socket.io-parser/build/cjs/is-binary.js | 55 + .../socket.io-parser/build/cjs/package.json | 3 + .../build/esm-debug/binary.d.ts | 20 + .../build/esm-debug/binary.js | 83 + .../build/esm-debug/index.d.ts | 90 + .../socket.io-parser/build/esm-debug/index.js | 293 ++ .../build/esm-debug/is-binary.d.ts | 7 + .../build/esm-debug/is-binary.js | 50 + .../build/esm-debug/package.json | 3 + .../socket.io-parser/build/esm/binary.d.ts | 20 + .../socket.io-parser/build/esm/binary.js | 83 + .../socket.io-parser/build/esm/index.d.ts | 90 + .../socket.io-parser/build/esm/index.js | 288 ++ .../socket.io-parser/build/esm/is-binary.d.ts | 7 + .../socket.io-parser/build/esm/is-binary.js | 50 + .../socket.io-parser/build/esm/package.json | 3 + node_modules/socket.io-parser/package.json | 55 + node_modules/web-streams-polyfill/LICENSE | 22 + node_modules/web-streams-polyfill/README.md | 114 + .../dist/polyfill.es2018.js | 4241 ++++++++++++++++ .../dist/polyfill.es2018.js.map | 1 + .../dist/polyfill.es2018.min.js | 2 + .../dist/polyfill.es2018.min.js.map | 1 + .../dist/polyfill.es2018.mjs | 4219 ++++++++++++++++ .../dist/polyfill.es2018.mjs.map | 1 + .../web-streams-polyfill/dist/polyfill.es6.js | 4252 ++++++++++++++++ .../dist/polyfill.es6.js.map | 1 + .../dist/polyfill.es6.min.js | 2 + .../dist/polyfill.es6.min.js.map | 1 + .../dist/polyfill.es6.mjs | 4230 ++++++++++++++++ .../dist/polyfill.es6.mjs.map | 1 + .../web-streams-polyfill/dist/polyfill.js | 4382 ++++++++++++++++ .../web-streams-polyfill/dist/polyfill.js.map | 1 + .../web-streams-polyfill/dist/polyfill.min.js | 2 + .../dist/polyfill.min.js.map | 1 + .../web-streams-polyfill/dist/polyfill.mjs | 4360 ++++++++++++++++ .../dist/polyfill.mjs.map | 1 + .../dist/ponyfill.es2018.js | 4213 ++++++++++++++++ .../dist/ponyfill.es2018.js.map | 1 + .../dist/ponyfill.es2018.mjs | 4191 ++++++++++++++++ .../dist/ponyfill.es2018.mjs.map | 1 + .../web-streams-polyfill/dist/ponyfill.es6.js | 4224 ++++++++++++++++ .../dist/ponyfill.es6.js.map | 1 + .../dist/ponyfill.es6.mjs | 4202 ++++++++++++++++ .../dist/ponyfill.es6.mjs.map | 1 + .../web-streams-polyfill/dist/ponyfill.js | 4354 ++++++++++++++++ .../web-streams-polyfill/dist/ponyfill.js.map | 1 + .../web-streams-polyfill/dist/ponyfill.mjs | 4332 ++++++++++++++++ .../dist/ponyfill.mjs.map | 1 + .../dist/types/polyfill.d.ts | 771 +++ .../dist/types/ts3.6/polyfill.d.ts | 771 +++ .../dist/types/tsdoc-metadata.json | 11 + .../web-streams-polyfill/es2018/package.json | 7 + .../web-streams-polyfill/es6/package.json | 7 + .../web-streams-polyfill/package.json | 76 + .../ponyfill/es2018/package.json | 6 + .../ponyfill/es6/package.json | 6 + .../ponyfill/package.json | 6 + node_modules/ws/LICENSE | 19 + node_modules/ws/README.md | 493 ++ node_modules/ws/browser.js | 8 + node_modules/ws/index.js | 13 + node_modules/ws/lib/buffer-util.js | 126 + node_modules/ws/lib/constants.js | 12 + node_modules/ws/lib/event-target.js | 266 + node_modules/ws/lib/extension.js | 203 + node_modules/ws/lib/limiter.js | 55 + node_modules/ws/lib/permessage-deflate.js | 511 ++ node_modules/ws/lib/receiver.js | 612 +++ node_modules/ws/lib/sender.js | 422 ++ node_modules/ws/lib/stream.js | 180 + node_modules/ws/lib/subprotocol.js | 62 + node_modules/ws/lib/validation.js | 124 + node_modules/ws/lib/websocket-server.js | 485 ++ node_modules/ws/lib/websocket.js | 1149 +++++ node_modules/ws/package.json | 61 + node_modules/ws/wrapper.mjs | 8 + node_modules/xmlhttprequest-ssl/LICENSE | 22 + node_modules/xmlhttprequest-ssl/README.md | 67 + .../xmlhttprequest-ssl/autotest.watchr | 8 + .../xmlhttprequest-ssl/example/demo.js | 16 + .../xmlhttprequest-ssl/lib/XMLHttpRequest.js | 673 +++ node_modules/xmlhttprequest-ssl/package.json | 35 + .../tests/test-constants.js | 13 + .../xmlhttprequest-ssl/tests/test-events.js | 50 + .../tests/test-exceptions.js | 59 + .../xmlhttprequest-ssl/tests/test-headers.js | 76 + .../tests/test-redirect-302.js | 41 + .../tests/test-redirect-303.js | 41 + .../tests/test-redirect-307.js | 43 + .../tests/test-request-methods.js | 62 + .../tests/test-request-protocols.js | 32 + .../xmlhttprequest-ssl/tests/testdata.txt | 1 + package-lock.json | 363 ++ package.json | 19 + wrapper.js | 195 + 580 files changed, 144174 insertions(+) create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@socket.io/component-emitter/LICENSE create mode 100644 node_modules/@socket.io/component-emitter/Readme.md create mode 100644 node_modules/@socket.io/component-emitter/index.d.ts create mode 100644 node_modules/@socket.io/component-emitter/index.js create mode 100644 node_modules/@socket.io/component-emitter/index.mjs create mode 100644 node_modules/@socket.io/component-emitter/package.json create mode 100755 node_modules/@types/node/LICENSE create mode 100755 node_modules/@types/node/README.md create mode 100755 node_modules/@types/node/assert.d.ts create mode 100755 node_modules/@types/node/assert/strict.d.ts create mode 100755 node_modules/@types/node/async_hooks.d.ts create mode 100755 node_modules/@types/node/buffer.d.ts create mode 100755 node_modules/@types/node/child_process.d.ts create mode 100755 node_modules/@types/node/cluster.d.ts create mode 100755 node_modules/@types/node/console.d.ts create mode 100755 node_modules/@types/node/constants.d.ts create mode 100755 node_modules/@types/node/crypto.d.ts create mode 100755 node_modules/@types/node/dgram.d.ts create mode 100755 node_modules/@types/node/diagnostics_channel.d.ts create mode 100755 node_modules/@types/node/dns.d.ts create mode 100755 node_modules/@types/node/dns/promises.d.ts create mode 100755 node_modules/@types/node/domain.d.ts create mode 100755 node_modules/@types/node/events.d.ts create mode 100755 node_modules/@types/node/fs.d.ts create mode 100755 node_modules/@types/node/fs/promises.d.ts create mode 100755 node_modules/@types/node/globals.d.ts create mode 100755 node_modules/@types/node/globals.global.d.ts create mode 100755 node_modules/@types/node/http.d.ts create mode 100755 node_modules/@types/node/http2.d.ts create mode 100755 node_modules/@types/node/https.d.ts create mode 100755 node_modules/@types/node/index.d.ts create mode 100755 node_modules/@types/node/inspector.d.ts create mode 100755 node_modules/@types/node/module.d.ts create mode 100755 node_modules/@types/node/net.d.ts create mode 100755 node_modules/@types/node/os.d.ts create mode 100755 node_modules/@types/node/package.json create mode 100755 node_modules/@types/node/path.d.ts create mode 100755 node_modules/@types/node/perf_hooks.d.ts create mode 100755 node_modules/@types/node/process.d.ts create mode 100755 node_modules/@types/node/punycode.d.ts create mode 100755 node_modules/@types/node/querystring.d.ts create mode 100755 node_modules/@types/node/readline.d.ts create mode 100755 node_modules/@types/node/readline/promises.d.ts create mode 100755 node_modules/@types/node/repl.d.ts create mode 100755 node_modules/@types/node/stream.d.ts create mode 100755 node_modules/@types/node/stream/consumers.d.ts create mode 100755 node_modules/@types/node/stream/promises.d.ts create mode 100755 node_modules/@types/node/stream/web.d.ts create mode 100755 node_modules/@types/node/string_decoder.d.ts create mode 100755 node_modules/@types/node/test.d.ts create mode 100755 node_modules/@types/node/timers.d.ts create mode 100755 node_modules/@types/node/timers/promises.d.ts create mode 100755 node_modules/@types/node/tls.d.ts create mode 100755 node_modules/@types/node/trace_events.d.ts create mode 100755 node_modules/@types/node/tty.d.ts create mode 100755 node_modules/@types/node/url.d.ts create mode 100755 node_modules/@types/node/util.d.ts create mode 100755 node_modules/@types/node/v8.d.ts create mode 100755 node_modules/@types/node/vm.d.ts create mode 100755 node_modules/@types/node/wasi.d.ts create mode 100755 node_modules/@types/node/worker_threads.d.ts create mode 100755 node_modules/@types/node/zlib.d.ts create mode 100644 node_modules/data-uri-to-buffer/README.md create mode 100644 node_modules/data-uri-to-buffer/dist/index.d.ts create mode 100644 node_modules/data-uri-to-buffer/dist/index.js create mode 100644 node_modules/data-uri-to-buffer/dist/index.js.map create mode 100644 node_modules/data-uri-to-buffer/dist/src/index.d.ts create mode 100644 node_modules/data-uri-to-buffer/dist/src/index.js create mode 100644 node_modules/data-uri-to-buffer/dist/src/index.js.map create mode 100644 node_modules/data-uri-to-buffer/dist/test/test.d.ts create mode 100644 node_modules/data-uri-to-buffer/dist/test/test.js create mode 100644 node_modules/data-uri-to-buffer/dist/test/test.js.map create mode 100644 node_modules/data-uri-to-buffer/package.json create mode 100644 node_modules/data-uri-to-buffer/src/index.ts create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/common.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/dotenv/CHANGELOG.md create mode 100644 node_modules/dotenv/LICENSE create mode 100644 node_modules/dotenv/README.md create mode 100644 node_modules/dotenv/config.d.ts create mode 100644 node_modules/dotenv/config.js create mode 100644 node_modules/dotenv/lib/cli-options.js create mode 100644 node_modules/dotenv/lib/env-options.js create mode 100644 node_modules/dotenv/lib/main.d.ts create mode 100644 node_modules/dotenv/lib/main.js create mode 100644 node_modules/dotenv/package.json create mode 100644 node_modules/engine.io-client/LICENSE create mode 100644 node_modules/engine.io-client/README.md create mode 100644 node_modules/engine.io-client/build/cjs/browser-entrypoint.js create mode 100644 node_modules/engine.io-client/build/cjs/contrib/has-cors.js create mode 100644 node_modules/engine.io-client/build/cjs/contrib/parseqs.js create mode 100644 node_modules/engine.io-client/build/cjs/contrib/parseuri.js create mode 100644 node_modules/engine.io-client/build/cjs/contrib/yeast.js create mode 100644 node_modules/engine.io-client/build/cjs/globalThis.browser.js create mode 100644 node_modules/engine.io-client/build/cjs/globalThis.js create mode 100644 node_modules/engine.io-client/build/cjs/index.js create mode 100644 node_modules/engine.io-client/build/cjs/package.json create mode 100644 node_modules/engine.io-client/build/cjs/socket.js create mode 100644 node_modules/engine.io-client/build/cjs/transport.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/index.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/polling.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/websocket-constructor.browser.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/websocket-constructor.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/websocket.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.browser.js create mode 100644 node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.js create mode 100644 node_modules/engine.io-client/build/cjs/util.js create mode 100644 node_modules/engine.io-client/build/esm-debug/browser-entrypoint.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/browser-entrypoint.js create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/has-cors.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/has-cors.js create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/parseqs.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/parseqs.js create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/parseuri.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/parseuri.js create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/yeast.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/contrib/yeast.js create mode 100644 node_modules/engine.io-client/build/esm-debug/globalThis.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/globalThis.browser.js create mode 100644 node_modules/engine.io-client/build/esm-debug/globalThis.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/globalThis.js create mode 100644 node_modules/engine.io-client/build/esm-debug/index.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/index.js create mode 100644 node_modules/engine.io-client/build/esm-debug/package.json create mode 100644 node_modules/engine.io-client/build/esm-debug/socket.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/socket.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transport.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transport.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/index.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/index.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/polling.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/polling.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/websocket.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.js create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.js create mode 100644 node_modules/engine.io-client/build/esm-debug/util.d.ts create mode 100644 node_modules/engine.io-client/build/esm-debug/util.js create mode 100644 node_modules/engine.io-client/build/esm/browser-entrypoint.d.ts create mode 100644 node_modules/engine.io-client/build/esm/browser-entrypoint.js create mode 100644 node_modules/engine.io-client/build/esm/contrib/has-cors.d.ts create mode 100644 node_modules/engine.io-client/build/esm/contrib/has-cors.js create mode 100644 node_modules/engine.io-client/build/esm/contrib/parseqs.d.ts create mode 100644 node_modules/engine.io-client/build/esm/contrib/parseqs.js create mode 100644 node_modules/engine.io-client/build/esm/contrib/parseuri.d.ts create mode 100644 node_modules/engine.io-client/build/esm/contrib/parseuri.js create mode 100644 node_modules/engine.io-client/build/esm/contrib/yeast.d.ts create mode 100644 node_modules/engine.io-client/build/esm/contrib/yeast.js create mode 100644 node_modules/engine.io-client/build/esm/globalThis.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm/globalThis.browser.js create mode 100644 node_modules/engine.io-client/build/esm/globalThis.d.ts create mode 100644 node_modules/engine.io-client/build/esm/globalThis.js create mode 100644 node_modules/engine.io-client/build/esm/index.d.ts create mode 100644 node_modules/engine.io-client/build/esm/index.js create mode 100644 node_modules/engine.io-client/build/esm/package.json create mode 100644 node_modules/engine.io-client/build/esm/socket.d.ts create mode 100644 node_modules/engine.io-client/build/esm/socket.js create mode 100644 node_modules/engine.io-client/build/esm/transport.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transport.js create mode 100644 node_modules/engine.io-client/build/esm/transports/index.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/index.js create mode 100644 node_modules/engine.io-client/build/esm/transports/polling.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/polling.js create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket-constructor.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket-constructor.js create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/websocket.js create mode 100644 node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js create mode 100644 node_modules/engine.io-client/build/esm/transports/xmlhttprequest.d.ts create mode 100644 node_modules/engine.io-client/build/esm/transports/xmlhttprequest.js create mode 100644 node_modules/engine.io-client/build/esm/util.d.ts create mode 100644 node_modules/engine.io-client/build/esm/util.js create mode 100644 node_modules/engine.io-client/dist/engine.io.esm.min.js create mode 100644 node_modules/engine.io-client/dist/engine.io.esm.min.js.map create mode 100644 node_modules/engine.io-client/dist/engine.io.js create mode 100644 node_modules/engine.io-client/dist/engine.io.js.map create mode 100644 node_modules/engine.io-client/dist/engine.io.min.js create mode 100644 node_modules/engine.io-client/dist/engine.io.min.js.map create mode 100644 node_modules/engine.io-client/package.json create mode 100644 node_modules/engine.io-parser/LICENSE create mode 100644 node_modules/engine.io-parser/Readme.md create mode 100644 node_modules/engine.io-parser/build/cjs/commons.js create mode 100644 node_modules/engine.io-parser/build/cjs/contrib/base64-arraybuffer.js create mode 100644 node_modules/engine.io-parser/build/cjs/decodePacket.browser.js create mode 100644 node_modules/engine.io-parser/build/cjs/decodePacket.js create mode 100644 node_modules/engine.io-parser/build/cjs/encodePacket.browser.js create mode 100644 node_modules/engine.io-parser/build/cjs/encodePacket.js create mode 100644 node_modules/engine.io-parser/build/cjs/index.js create mode 100644 node_modules/engine.io-parser/build/cjs/package.json create mode 100644 node_modules/engine.io-parser/build/esm/commons.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/commons.js create mode 100644 node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js create mode 100644 node_modules/engine.io-parser/build/esm/decodePacket.browser.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/decodePacket.browser.js create mode 100644 node_modules/engine.io-parser/build/esm/decodePacket.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/decodePacket.js create mode 100644 node_modules/engine.io-parser/build/esm/encodePacket.browser.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/encodePacket.browser.js create mode 100644 node_modules/engine.io-parser/build/esm/encodePacket.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/encodePacket.js create mode 100644 node_modules/engine.io-parser/build/esm/index.d.ts create mode 100644 node_modules/engine.io-parser/build/esm/index.js create mode 100644 node_modules/engine.io-parser/build/esm/package.json create mode 100644 node_modules/engine.io-parser/package.json create mode 100644 node_modules/fetch-blob/LICENSE create mode 100644 node_modules/fetch-blob/README.md create mode 100644 node_modules/fetch-blob/file.d.ts create mode 100644 node_modules/fetch-blob/file.js create mode 100644 node_modules/fetch-blob/from.d.ts create mode 100644 node_modules/fetch-blob/from.js create mode 100644 node_modules/fetch-blob/index.d.ts create mode 100644 node_modules/fetch-blob/index.js create mode 100644 node_modules/fetch-blob/package.json create mode 100644 node_modules/fetch-blob/streams.cjs create mode 100644 node_modules/formdata-polyfill/FormData.js create mode 100644 node_modules/formdata-polyfill/LICENSE create mode 100644 node_modules/formdata-polyfill/README.md create mode 100644 node_modules/formdata-polyfill/esm.min.d.ts create mode 100644 node_modules/formdata-polyfill/esm.min.js create mode 100644 node_modules/formdata-polyfill/formdata-to-blob.js create mode 100644 node_modules/formdata-polyfill/formdata.min.js create mode 100644 node_modules/formdata-polyfill/package.json create mode 100644 node_modules/heap/.npmignore create mode 100644 node_modules/heap/.travis.yml create mode 100644 node_modules/heap/Makefile create mode 100644 node_modules/heap/README.md create mode 100644 node_modules/heap/bower.json create mode 100644 node_modules/heap/index.js create mode 100644 node_modules/heap/lib/heap.js create mode 100644 node_modules/heap/package.json create mode 100644 node_modules/heap/src/heap.coffee create mode 100644 node_modules/heap/test/heap.test.coffee create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/node-domexception/.history/README_20210527203617.md create mode 100644 node_modules/node-domexception/.history/README_20210527212714.md create mode 100644 node_modules/node-domexception/.history/README_20210527213345.md create mode 100644 node_modules/node-domexception/.history/README_20210527213411.md create mode 100644 node_modules/node-domexception/.history/README_20210527213803.md create mode 100644 node_modules/node-domexception/.history/README_20210527214323.md create mode 100644 node_modules/node-domexception/.history/README_20210527214408.md create mode 100644 node_modules/node-domexception/.history/index_20210527203842.js create mode 100644 node_modules/node-domexception/.history/index_20210527203947.js create mode 100644 node_modules/node-domexception/.history/index_20210527204259.js create mode 100644 node_modules/node-domexception/.history/index_20210527204418.js create mode 100644 node_modules/node-domexception/.history/index_20210527204756.js create mode 100644 node_modules/node-domexception/.history/index_20210527204833.js create mode 100644 node_modules/node-domexception/.history/index_20210527211208.js create mode 100644 node_modules/node-domexception/.history/index_20210527211248.js create mode 100644 node_modules/node-domexception/.history/index_20210527212722.js create mode 100644 node_modules/node-domexception/.history/index_20210527212731.js create mode 100644 node_modules/node-domexception/.history/index_20210527212746.js create mode 100644 node_modules/node-domexception/.history/index_20210527212900.js create mode 100644 node_modules/node-domexception/.history/index_20210527213022.js create mode 100644 node_modules/node-domexception/.history/index_20210527213822.js create mode 100644 node_modules/node-domexception/.history/index_20210527213843.js create mode 100644 node_modules/node-domexception/.history/index_20210527213852.js create mode 100644 node_modules/node-domexception/.history/index_20210527213910.js create mode 100644 node_modules/node-domexception/.history/index_20210527214034.js create mode 100644 node_modules/node-domexception/.history/index_20210527214643.js create mode 100644 node_modules/node-domexception/.history/index_20210527214654.js create mode 100644 node_modules/node-domexception/.history/index_20210527214700.js create mode 100644 node_modules/node-domexception/.history/package_20210527203733.json create mode 100644 node_modules/node-domexception/.history/package_20210527203825.json create mode 100644 node_modules/node-domexception/.history/package_20210527204621.json create mode 100644 node_modules/node-domexception/.history/package_20210527204913.json create mode 100644 node_modules/node-domexception/.history/package_20210527204925.json create mode 100644 node_modules/node-domexception/.history/package_20210527205145.json create mode 100644 node_modules/node-domexception/.history/package_20210527205156.json create mode 100644 node_modules/node-domexception/.history/test_20210527205603.js create mode 100644 node_modules/node-domexception/.history/test_20210527205957.js create mode 100644 node_modules/node-domexception/.history/test_20210527210021.js create mode 100644 node_modules/node-domexception/LICENSE create mode 100644 node_modules/node-domexception/README.md create mode 100644 node_modules/node-domexception/index.js create mode 100644 node_modules/node-domexception/package.json create mode 100644 node_modules/node-fetch/@types/index.d.ts create mode 100644 node_modules/node-fetch/LICENSE.md create mode 100644 node_modules/node-fetch/README.md create mode 100644 node_modules/node-fetch/package.json create mode 100644 node_modules/node-fetch/src/body.js create mode 100644 node_modules/node-fetch/src/errors/abort-error.js create mode 100644 node_modules/node-fetch/src/errors/base.js create mode 100644 node_modules/node-fetch/src/errors/fetch-error.js create mode 100644 node_modules/node-fetch/src/headers.js create mode 100644 node_modules/node-fetch/src/index.js create mode 100644 node_modules/node-fetch/src/request.js create mode 100644 node_modules/node-fetch/src/response.js create mode 100644 node_modules/node-fetch/src/utils/get-search.js create mode 100644 node_modules/node-fetch/src/utils/is-redirect.js create mode 100644 node_modules/node-fetch/src/utils/is.js create mode 100644 node_modules/node-fetch/src/utils/multipart-parser.js create mode 100644 node_modules/node-fetch/src/utils/referrer.js create mode 100644 node_modules/pathfinding/.npmignore create mode 100644 node_modules/pathfinding/.travis.yml create mode 100644 node_modules/pathfinding/README.md create mode 100644 node_modules/pathfinding/TODO create mode 100644 node_modules/pathfinding/benchmark/benchmark.js create mode 100644 node_modules/pathfinding/benchmark/map/64room_000.map create mode 100644 node_modules/pathfinding/benchmark/map/arena.map create mode 100644 node_modules/pathfinding/benchmark/map/lak304d.map create mode 100644 node_modules/pathfinding/benchmark/map/losttemple.map create mode 100644 node_modules/pathfinding/benchmark/parse_map.js create mode 100644 node_modules/pathfinding/benchmark/parse_scen.js create mode 100644 node_modules/pathfinding/benchmark/scen/64room_000.map.scen create mode 100644 node_modules/pathfinding/benchmark/scen/arena.map.scen create mode 100644 node_modules/pathfinding/benchmark/scen/lak304d.map.scen create mode 100644 node_modules/pathfinding/benchmark/scen/losttemple.map.scen create mode 100644 node_modules/pathfinding/benchmark/test_cases.js create mode 100644 node_modules/pathfinding/docs/contributor-guide/authors.md create mode 100644 node_modules/pathfinding/docs/contributor-guide/contributing.md create mode 100644 node_modules/pathfinding/docs/contributor-guide/developing.md create mode 100644 node_modules/pathfinding/docs/custom.css create mode 100644 node_modules/pathfinding/docs/index.md create mode 100644 node_modules/pathfinding/docs/user-guide/diagonal-movement.md create mode 100644 node_modules/pathfinding/docs/user-guide/faq.md create mode 100644 node_modules/pathfinding/docs/user-guide/getting-started.md create mode 100644 node_modules/pathfinding/docs/user-guide/images/5x7EmptyGrid.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/5x7GridWithObstacles.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/5x7GridWithObstaclesAndPath.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/5x7GridWithPath.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/AllMapsWithAPath.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/AllMapsWithStraightPaths.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/DiagonalMaps.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/DiagonalMovementDisabled.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/DiagonalPathsForAtMostOneObstacle.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/DiagonalPathsForOnlyWhenNoObstacles.png create mode 100644 node_modules/pathfinding/docs/user-guide/images/images.svg create mode 100644 node_modules/pathfinding/docs/user-guide/installation.md create mode 100644 node_modules/pathfinding/docs/user-guide/introduction.md create mode 100644 node_modules/pathfinding/docs/user-guide/obstacles.md create mode 100644 node_modules/pathfinding/gulpfile.js create mode 100644 node_modules/pathfinding/index.js create mode 100644 node_modules/pathfinding/mkdocs.yml create mode 100644 node_modules/pathfinding/package.json create mode 100644 node_modules/pathfinding/src/PathFinding.js create mode 100644 node_modules/pathfinding/src/banner create mode 100644 node_modules/pathfinding/src/core/DiagonalMovement.js create mode 100644 node_modules/pathfinding/src/core/Grid.js create mode 100644 node_modules/pathfinding/src/core/Heuristic.js create mode 100644 node_modules/pathfinding/src/core/Node.js create mode 100644 node_modules/pathfinding/src/core/Util.js create mode 100644 node_modules/pathfinding/src/finders/AStarFinder.js create mode 100644 node_modules/pathfinding/src/finders/BestFirstFinder.js create mode 100644 node_modules/pathfinding/src/finders/BiAStarFinder.js create mode 100644 node_modules/pathfinding/src/finders/BiBestFirstFinder.js create mode 100644 node_modules/pathfinding/src/finders/BiBreadthFirstFinder.js create mode 100644 node_modules/pathfinding/src/finders/BiDijkstraFinder.js create mode 100644 node_modules/pathfinding/src/finders/BreadthFirstFinder.js create mode 100644 node_modules/pathfinding/src/finders/DijkstraFinder.js create mode 100644 node_modules/pathfinding/src/finders/IDAStarFinder.js create mode 100644 node_modules/pathfinding/src/finders/JPFAlwaysMoveDiagonally.js create mode 100644 node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfAtMostOneObstacle.js create mode 100644 node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfNoObstacles.js create mode 100644 node_modules/pathfinding/src/finders/JPFNeverMoveDiagonally.js create mode 100644 node_modules/pathfinding/src/finders/JumpPointFinder.js create mode 100644 node_modules/pathfinding/src/finders/JumpPointFinderBase.js create mode 100644 node_modules/pathfinding/test/Grid.js create mode 100644 node_modules/pathfinding/test/PathTest.js create mode 100644 node_modules/pathfinding/test/PathTestScenarios.js create mode 100644 node_modules/pathfinding/test/Util.js create mode 100644 node_modules/pathfinding/visual/Makefile create mode 100644 node_modules/pathfinding/visual/css/style.css create mode 100644 node_modules/pathfinding/visual/doc/state-description.md create mode 100644 node_modules/pathfinding/visual/doc/state-diagram.gv create mode 100644 node_modules/pathfinding/visual/doc/state-diagram.png create mode 100644 node_modules/pathfinding/visual/index.html create mode 100644 node_modules/pathfinding/visual/js/controller.js create mode 100644 node_modules/pathfinding/visual/js/main.js create mode 100644 node_modules/pathfinding/visual/js/panel.js create mode 100644 node_modules/pathfinding/visual/js/view.js create mode 100644 node_modules/pathfinding/visual/lib/async.min.js create mode 100644 node_modules/pathfinding/visual/lib/es5-shim.min.js create mode 100644 node_modules/pathfinding/visual/lib/jquery-1.7.2.min.js create mode 100644 node_modules/pathfinding/visual/lib/pathfinding-browser.min.js create mode 100644 node_modules/pathfinding/visual/lib/raphael-min.js create mode 100644 node_modules/pathfinding/visual/lib/state-machine.min.js create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_flat_0_aaaaaa_40x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_glass_95_fef1ec_1x400.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_gloss-wave_16_121212_500x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-hard_15_888888_1x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-hard_55_555555_1x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-soft_35_adadad_1x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-soft_60_dddddd_1x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-bg_inset-soft_15_121212_1x100.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_666666_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_aaaaaa_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_bbbbbb_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_c98000_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_cccccc_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_cd0a0a_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/images/ui-icons_f29a00_256x240.png create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.accordion.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.all.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.autocomplete.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.base.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.button.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.core.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.datepicker.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.dialog.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.progressbar.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.resizable.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.selectable.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.slider.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.tabs.css create mode 100644 node_modules/pathfinding/visual/lib/themes/jquery.ui.theme.css create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.accordion.min.js create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.core.min.js create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.draggable.min.js create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.mouse.min.js create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.slider.min.js create mode 100644 node_modules/pathfinding/visual/lib/ui/jquery.ui.widget.min.js create mode 100644 node_modules/pathfinding/visual/notsupported.html create mode 100644 node_modules/socket.io-client/LICENSE create mode 100644 node_modules/socket.io-client/README.md create mode 100644 node_modules/socket.io-client/build/cjs/browser-entrypoint.js create mode 100644 node_modules/socket.io-client/build/cjs/contrib/backo2.js create mode 100644 node_modules/socket.io-client/build/cjs/index.js create mode 100644 node_modules/socket.io-client/build/cjs/manager.js create mode 100644 node_modules/socket.io-client/build/cjs/on.js create mode 100644 node_modules/socket.io-client/build/cjs/socket.js create mode 100644 node_modules/socket.io-client/build/cjs/url.js create mode 100644 node_modules/socket.io-client/build/esm-debug/browser-entrypoint.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/browser-entrypoint.js create mode 100644 node_modules/socket.io-client/build/esm-debug/contrib/backo2.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/contrib/backo2.js create mode 100644 node_modules/socket.io-client/build/esm-debug/index.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/index.js create mode 100644 node_modules/socket.io-client/build/esm-debug/manager.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/manager.js create mode 100644 node_modules/socket.io-client/build/esm-debug/on.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/on.js create mode 100644 node_modules/socket.io-client/build/esm-debug/package.json create mode 100644 node_modules/socket.io-client/build/esm-debug/socket.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/socket.js create mode 100644 node_modules/socket.io-client/build/esm-debug/url.d.ts create mode 100644 node_modules/socket.io-client/build/esm-debug/url.js create mode 100644 node_modules/socket.io-client/build/esm/browser-entrypoint.d.ts create mode 100644 node_modules/socket.io-client/build/esm/browser-entrypoint.js create mode 100644 node_modules/socket.io-client/build/esm/contrib/backo2.d.ts create mode 100644 node_modules/socket.io-client/build/esm/contrib/backo2.js create mode 100644 node_modules/socket.io-client/build/esm/index.d.ts create mode 100644 node_modules/socket.io-client/build/esm/index.js create mode 100644 node_modules/socket.io-client/build/esm/manager.d.ts create mode 100644 node_modules/socket.io-client/build/esm/manager.js create mode 100644 node_modules/socket.io-client/build/esm/on.d.ts create mode 100644 node_modules/socket.io-client/build/esm/on.js create mode 100644 node_modules/socket.io-client/build/esm/package.json create mode 100644 node_modules/socket.io-client/build/esm/socket.d.ts create mode 100644 node_modules/socket.io-client/build/esm/socket.js create mode 100644 node_modules/socket.io-client/build/esm/url.d.ts create mode 100644 node_modules/socket.io-client/build/esm/url.js create mode 100644 node_modules/socket.io-client/dist/socket.io.esm.min.js create mode 100644 node_modules/socket.io-client/dist/socket.io.esm.min.js.map create mode 100644 node_modules/socket.io-client/dist/socket.io.js create mode 100644 node_modules/socket.io-client/dist/socket.io.js.map create mode 100644 node_modules/socket.io-client/dist/socket.io.min.js create mode 100644 node_modules/socket.io-client/dist/socket.io.min.js.map create mode 100644 node_modules/socket.io-client/dist/socket.io.msgpack.min.js create mode 100644 node_modules/socket.io-client/dist/socket.io.msgpack.min.js.map create mode 100644 node_modules/socket.io-client/package.json create mode 100644 node_modules/socket.io-parser/LICENSE create mode 100644 node_modules/socket.io-parser/Readme.md create mode 100644 node_modules/socket.io-parser/build/cjs/binary.js create mode 100644 node_modules/socket.io-parser/build/cjs/index.js create mode 100644 node_modules/socket.io-parser/build/cjs/is-binary.js create mode 100644 node_modules/socket.io-parser/build/cjs/package.json create mode 100644 node_modules/socket.io-parser/build/esm-debug/binary.d.ts create mode 100644 node_modules/socket.io-parser/build/esm-debug/binary.js create mode 100644 node_modules/socket.io-parser/build/esm-debug/index.d.ts create mode 100644 node_modules/socket.io-parser/build/esm-debug/index.js create mode 100644 node_modules/socket.io-parser/build/esm-debug/is-binary.d.ts create mode 100644 node_modules/socket.io-parser/build/esm-debug/is-binary.js create mode 100644 node_modules/socket.io-parser/build/esm-debug/package.json create mode 100644 node_modules/socket.io-parser/build/esm/binary.d.ts create mode 100644 node_modules/socket.io-parser/build/esm/binary.js create mode 100644 node_modules/socket.io-parser/build/esm/index.d.ts create mode 100644 node_modules/socket.io-parser/build/esm/index.js create mode 100644 node_modules/socket.io-parser/build/esm/is-binary.d.ts create mode 100644 node_modules/socket.io-parser/build/esm/is-binary.js create mode 100644 node_modules/socket.io-parser/build/esm/package.json create mode 100644 node_modules/socket.io-parser/package.json create mode 100644 node_modules/web-streams-polyfill/LICENSE create mode 100644 node_modules/web-streams-polyfill/README.md create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.min.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.mjs create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.min.js create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.min.js.map create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.mjs create mode 100644 node_modules/web-streams-polyfill/dist/polyfill.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es2018.js create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es6.js create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.js create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.js.map create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.mjs create mode 100644 node_modules/web-streams-polyfill/dist/ponyfill.mjs.map create mode 100644 node_modules/web-streams-polyfill/dist/types/polyfill.d.ts create mode 100644 node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts create mode 100644 node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json create mode 100644 node_modules/web-streams-polyfill/es2018/package.json create mode 100644 node_modules/web-streams-polyfill/es6/package.json create mode 100644 node_modules/web-streams-polyfill/package.json create mode 100644 node_modules/web-streams-polyfill/ponyfill/es2018/package.json create mode 100644 node_modules/web-streams-polyfill/ponyfill/es6/package.json create mode 100644 node_modules/web-streams-polyfill/ponyfill/package.json create mode 100644 node_modules/ws/LICENSE create mode 100644 node_modules/ws/README.md create mode 100644 node_modules/ws/browser.js create mode 100644 node_modules/ws/index.js create mode 100644 node_modules/ws/lib/buffer-util.js create mode 100644 node_modules/ws/lib/constants.js create mode 100644 node_modules/ws/lib/event-target.js create mode 100644 node_modules/ws/lib/extension.js create mode 100644 node_modules/ws/lib/limiter.js create mode 100644 node_modules/ws/lib/permessage-deflate.js create mode 100644 node_modules/ws/lib/receiver.js create mode 100644 node_modules/ws/lib/sender.js create mode 100644 node_modules/ws/lib/stream.js create mode 100644 node_modules/ws/lib/subprotocol.js create mode 100644 node_modules/ws/lib/validation.js create mode 100644 node_modules/ws/lib/websocket-server.js create mode 100644 node_modules/ws/lib/websocket.js create mode 100644 node_modules/ws/package.json create mode 100644 node_modules/ws/wrapper.mjs create mode 100644 node_modules/xmlhttprequest-ssl/LICENSE create mode 100644 node_modules/xmlhttprequest-ssl/README.md create mode 100644 node_modules/xmlhttprequest-ssl/autotest.watchr create mode 100644 node_modules/xmlhttprequest-ssl/example/demo.js create mode 100644 node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js create mode 100644 node_modules/xmlhttprequest-ssl/package.json create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-constants.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-events.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-exceptions.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-headers.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-redirect-302.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-redirect-303.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-redirect-307.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-request-methods.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/test-request-protocols.js create mode 100644 node_modules/xmlhttprequest-ssl/tests/testdata.txt create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 wrapper.js diff --git a/index.js b/index.js index 8252a98..3fac019 100644 --- a/index.js +++ b/index.js @@ -15,6 +15,8 @@ const GOLDEN_FOOD = 4 const BLACK_HOLE = 5 const newSnake = require('./wrapper.js') +const dotenv = require('dotenv'); +dotenv.config(); let snake = newSnake(process.env.auth) // Login with the auth cookie in the secrets tab diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..744370b --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,218 @@ +{ + "name": "nodejs", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@socket.io/component-emitter": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", + "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" + }, + "node_modules/@types/node": { + "version": "18.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.5.tgz", + "integrity": "sha512-NcKK6Ts+9LqdHJaW6HQmgr7dT/i3GOHG+pt6BiWv++5SnjtRd4NXeiuN2kA153SjhXPR/AhHIPHPbrsbpUVOww==" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz", + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dotenv": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.1.tgz", + "integrity": "sha512-1K6hR6wtk2FviQ4kEiSjFiH5rpzEVi8WW0x96aztHVMhEspNpc4DVOUTEHtEva5VThQ8IaBX1Pe4gSzpVVUsKQ==", + "engines": { + "node": ">=12" + } + }, + "node_modules/engine.io-client": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.2.2.tgz", + "integrity": "sha512-8ZQmx0LQGRTYkHuogVZuGSpDqYZtCM/nv8zQ68VZ+JkOpazJ7ICdsSpaO6iXwvaU30oFg5QJOJWj8zWqhbKjkQ==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3", + "xmlhttprequest-ssl": "~2.0.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.4.tgz", + "integrity": "sha512-+nVFp+5z1E3HcToEnO7ZIj3g+3k9389DvWtvJZz0T6/eOCPIyyxehFcedoYrZQrp0LgQbD9pPXhpMBKMd5QURg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/heap": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/heap/-/heap-0.2.5.tgz", + "integrity": "sha512-G7HLD+WKcrOyJP5VQwYZNC3Z6FcQ7YYjEFiFoIj8PfEr73mu421o8B1N5DKUcc8K37EsJ2XXWA8DtrDz/2dReg==" + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.2.10", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.10.tgz", + "integrity": "sha512-MhuzNwdURnZ1Cp4XTazr69K0BTizsBroX7Zx3UgDSVcZYKF/6p0CBe4EUb/hLqmzVhl0UpYfgRljQ4yxE+iCxA==", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/pathfinding": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/pathfinding/-/pathfinding-0.4.18.tgz", + "integrity": "sha512-R0TGEQ9GRcFCDvAWlJAWC+KGJ9SLbW4c0nuZRcioVlXVTlw+F5RvXQ8SQgSqI9KXWC1ew95vgmIiyaWTlCe9Ag==", + "dependencies": { + "heap": "0.2.5" + } + }, + "node_modules/socket.io-client": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.5.1.tgz", + "integrity": "sha512-e6nLVgiRYatS+AHXnOnGi4ocOpubvOUCGhyWw8v+/FxW8saHkinG6Dfhi9TU0Kt/8mwJIAASxvw6eujQmjdZVA==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.2.1", + "socket.io-parser": "~4.2.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.1.tgz", + "integrity": "sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", + "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==", + "engines": { + "node": ">=0.4.0" + } + } + } +} diff --git a/node_modules/@socket.io/component-emitter/LICENSE b/node_modules/@socket.io/component-emitter/LICENSE new file mode 100644 index 0000000..de51692 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Component contributors + +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/node_modules/@socket.io/component-emitter/Readme.md b/node_modules/@socket.io/component-emitter/Readme.md new file mode 100644 index 0000000..0f3f9b9 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/Readme.md @@ -0,0 +1,74 @@ +# Emitter [![Build Status](https://travis-ci.org/component/emitter.png)](https://travis-ci.org/component/emitter) + + Event emitter component. + +## Installation + +``` +$ component install component/emitter +``` + +## API + +### Emitter(obj) + + The `Emitter` may also be used as a mixin. For example + a "plain" object may become an emitter, or you may + extend an existing prototype. + + As an `Emitter` instance: + +```js +var Emitter = require('emitter'); +var emitter = new Emitter; +emitter.emit('something'); +``` + + As a mixin: + +```js +var Emitter = require('emitter'); +var user = { name: 'tobi' }; +Emitter(user); + +user.emit('im a user'); +``` + + As a prototype mixin: + +```js +var Emitter = require('emitter'); +Emitter(User.prototype); +``` + +### Emitter#on(event, fn) + + Register an `event` handler `fn`. + +### Emitter#once(event, fn) + + Register a single-shot `event` handler `fn`, + removed immediately after it is invoked the + first time. + +### Emitter#off(event, fn) + + * Pass `event` and `fn` to remove a listener. + * Pass `event` to remove all listeners on that event. + * Pass nothing to remove all listeners on all events. + +### Emitter#emit(event, ...) + + Emit an `event` with variable option args. + +### Emitter#listeners(event) + + Return an array of callbacks, or an empty array. + +### Emitter#hasListeners(event) + + Check if this emitter has `event` handlers. + +## License + +MIT diff --git a/node_modules/@socket.io/component-emitter/index.d.ts b/node_modules/@socket.io/component-emitter/index.d.ts new file mode 100644 index 0000000..49a74e1 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/index.d.ts @@ -0,0 +1,179 @@ +/** + * An events map is an interface that maps event names to their value, which + * represents the type of the `on` listener. + */ +export interface EventsMap { + [event: string]: any; +} + +/** + * The default events map, used if no EventsMap is given. Using this EventsMap + * is equivalent to accepting all event names, and any data. + */ +export interface DefaultEventsMap { + [event: string]: (...args: any[]) => void; +} + +/** + * Returns a union type containing all the keys of an event map. + */ +export type EventNames = keyof Map & (string | symbol); + +/** The tuple type representing the parameters of an event listener */ +export type EventParams< + Map extends EventsMap, + Ev extends EventNames + > = Parameters; + +/** + * The event names that are either in ReservedEvents or in UserEvents + */ +export type ReservedOrUserEventNames< + ReservedEventsMap extends EventsMap, + UserEvents extends EventsMap + > = EventNames | EventNames; + +/** + * Type of a listener of a user event or a reserved event. If `Ev` is in + * `ReservedEvents`, the reserved event listener is returned. + */ +export type ReservedOrUserListener< + ReservedEvents extends EventsMap, + UserEvents extends EventsMap, + Ev extends ReservedOrUserEventNames + > = FallbackToUntypedListener< + Ev extends EventNames + ? ReservedEvents[Ev] + : Ev extends EventNames + ? UserEvents[Ev] + : never + >; + +/** + * Returns an untyped listener type if `T` is `never`; otherwise, returns `T`. + * + * This is a hack to mitigate https://github.com/socketio/socket.io/issues/3833. + * Needed because of https://github.com/microsoft/TypeScript/issues/41778 + */ +type FallbackToUntypedListener = [T] extends [never] + ? (...args: any[]) => void | Promise + : T; + +/** + * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type + * parameters for mappings of event names to event data types, and strictly + * types method calls to the `EventEmitter` according to these event maps. + * + * @typeParam ListenEvents - `EventsMap` of user-defined events that can be + * listened to with `on` or `once` + * @typeParam EmitEvents - `EventsMap` of user-defined events that can be + * emitted with `emit` + * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be + * emitted by socket.io with `emitReserved`, and can be listened to with + * `listen`. + */ +export class Emitter< + ListenEvents extends EventsMap, + EmitEvents extends EventsMap, + ReservedEvents extends EventsMap = {} + > { + /** + * Adds the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + on>( + ev: Ev, + listener: ReservedOrUserListener + ): this; + + /** + * Adds a one-time `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + once>( + ev: Ev, + listener: ReservedOrUserListener + ): this; + + /** + * Removes the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + off>( + ev?: Ev, + listener?: ReservedOrUserListener + ): this; + + /** + * Emits an event. + * + * @param ev Name of the event + * @param args Values to send to listeners of this event + */ + emit>( + ev: Ev, + ...args: EventParams + ): this; + + /** + * Emits a reserved event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can emit its own reserved events. + * + * @param ev Reserved event name + * @param args Arguments to emit along with the event + */ + protected emitReserved>( + ev: Ev, + ...args: EventParams + ): this; + + /** + * Returns the listeners listening to an event. + * + * @param event Event name + * @returns Array of listeners subscribed to `event` + */ + listeners>( + event: Ev + ): ReservedOrUserListener[]; + + /** + * Returns true if there is a listener for this event. + * + * @param event Event name + * @returns boolean + */ + hasListeners< + Ev extends ReservedOrUserEventNames + >(event: Ev): boolean; + + /** + * Removes the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + removeListener< + Ev extends ReservedOrUserEventNames + >( + ev?: Ev, + listener?: ReservedOrUserListener + ): this; + + /** + * Removes all `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + */ + removeAllListeners< + Ev extends ReservedOrUserEventNames + >(ev?: Ev): this; +} diff --git a/node_modules/@socket.io/component-emitter/index.js b/node_modules/@socket.io/component-emitter/index.js new file mode 100644 index 0000000..e0d5497 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/index.js @@ -0,0 +1,176 @@ + +/** + * Expose `Emitter`. + */ + +exports.Emitter = Emitter; + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +// alias used for reserved events (protected method) +Emitter.prototype.emitReserved = Emitter.prototype.emit; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; diff --git a/node_modules/@socket.io/component-emitter/index.mjs b/node_modules/@socket.io/component-emitter/index.mjs new file mode 100644 index 0000000..b2e5c3f --- /dev/null +++ b/node_modules/@socket.io/component-emitter/index.mjs @@ -0,0 +1,169 @@ +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +export function Emitter(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +// alias used for reserved events (protected method) +Emitter.prototype.emitReserved = Emitter.prototype.emit; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; diff --git a/node_modules/@socket.io/component-emitter/package.json b/node_modules/@socket.io/component-emitter/package.json new file mode 100644 index 0000000..c73c23d --- /dev/null +++ b/node_modules/@socket.io/component-emitter/package.json @@ -0,0 +1,31 @@ +{ + "name": "@socket.io/component-emitter", + "description": "Event emitter", + "version": "3.1.0", + "license": "MIT", + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "component": { + "scripts": { + "emitter/index.js": "index.js" + } + }, + "main": "index.js", + "module": "index.mjs", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/socketio/emitter.git" + }, + "scripts": { + "test": "make test" + }, + "files": [ + "index.js", + "index.mjs", + "index.d.ts", + "LICENSE" + ] +} diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100755 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100755 index 0000000..6378844 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Mon, 15 Aug 2022 18:32:42 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`, `structuredClone` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), and [Matteo Collina](https://github.com/mcollina). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100755 index 0000000..8e02a66 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,911 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js) + */ +declare module 'assert' { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100755 index 0000000..b4319b9 --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100755 index 0000000..0bf4739 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,501 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module 'node:async_hooks' { + export * from 'async_hooks'; +} diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100755 index 0000000..13ab335 --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2238 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): unknown; // pending web streams types + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100755 index 0000000..79c7290 --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1369 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; + type SerializationType = 'json' | 'advanced'; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: 'buffer' | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: ReadonlyArray): Buffer; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): string | Buffer; +} +declare module 'node:child_process' { + export * from 'child_process'; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100755 index 0000000..37dbc57 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,410 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process + * isolation is not needed, use the `worker_threads` module instead, which + * allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker, this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + addListener(event: 'listening', listener: (address: Address) => void): this; + addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => void): this; + on(event: 'listening', listener: (address: Address) => void): this; + on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => void): this; + once(event: 'listening', listener: (address: Address) => void): this; + once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependListener(event: 'listening', listener: (address: Address) => void): this; + prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'online', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependOnceListener(event: 'listening', listener: (address: Address) => void): this; + prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'online', listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', listener: (worker: Worker) => void): this; + on(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', listener: (worker: Worker) => void): this; + once(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this; + prependListener(event: 'online', listener: (worker: Worker) => void): this; + prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: 'online', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module 'node:cluster' { + export * from 'cluster'; + export { default as default } from 'cluster'; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100755 index 0000000..16c9137 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,412 @@ +/** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js) + */ +declare module 'console' { + import console = require('node:console'); + export = console; +} +declare module 'node:console' { + import { InspectOptions } from 'node:util'; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can’t be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100755 index 0000000..208020d --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'node:os'; + import { constants as cryptoConstants } from 'node:crypto'; + import { constants as fsConstants } from 'node:fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} + +declare module 'node:constants' { + import constants = require('constants'); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100755 index 0000000..e127518 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3964 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'buffer'; + * const { Certificate } = await import('crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = 'secret' | 'public' | 'private'; + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + type CipherOCBTypes = 'aes-128-ocb' | 'aes-192-ocb' | 'aes-256-ocb'; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): CipherOCB; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): DecipherOCB; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: 'hmac' | 'aes', + options: { + length: number; + } + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = 'der' | 'ieee-p1363'; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding: null, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url', + format?: 'uncompressed' | 'compressed' | 'hybrid' + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * @since v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. + * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * - `crypto.constants.ENGINE_METHOD_RSA` + * - `crypto.constants.ENGINE_METHOD_DSA` + * - `crypto.constants.ENGINE_METHOD_DH` + * - `crypto.constants.ENGINE_METHOD_RAND` + * - `crypto.constants.ENGINE_METHOD_EC` + * - `crypto.constants.ENGINE_METHOD_CIPHERS` + * - `crypto.constants.ENGINE_METHOD_DIGESTS` + * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * - `crypto.constants.ENGINE_METHOD_ALL` + * - `crypto.constants.ENGINE_METHOD_NONE` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for `crypto.webcrypto.getRandomValues()`. + * This implementation is not compliant with the Web Crypto spec, + * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * @since v17.4.0 + * @returns Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = 'jwk' | 'pkcs8' | 'raw' | 'spki'; + type KeyType = 'private' | 'public' | 'secret'; + type KeyUsage = 'decrypt' | 'deriveBits' | 'deriveKey' | 'encrypt' | 'sign' | 'unwrapKey' | 'verify' | 'wrapKey'; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): string; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: 'CryptoKey'; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that `length` is a multiple of `8`. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: 'jwk', key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: 'jwk', + keyData: JsonWebKey, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise; + } + } +} +declare module 'node:crypto' { + export * from 'crypto'; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100755 index 0000000..247328d --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} +declare module 'node:dgram' { + export * from 'dgram'; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100755 index 0000000..a87ba8c --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,153 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string): Channel; + type ChannelListener = (message: unknown, name: string) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string); + /** + * Publish a message to any subscribers to the channel. This will + * trigger message handlers synchronously so they will execute within + * the same context. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message' + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100755 index 0000000..305367b --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,659 @@ +/** + * The `dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses, and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; + } + export interface CaaRecord { + critial: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: 'MX'; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; + } + export interface AnyTxtRecord { + type: 'TXT'; + entries: string[]; + } + export interface AnyNsRecord { + type: 'NS'; + value: string; + } + export interface AnyPtrRecord { + type: 'PTR'; + value: string; + } + export interface AnyCnameRecord { + type: 'CNAME'; + value: string; + } + export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: ReadonlyArray): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default + * dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default, and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module 'node:dns' { + export * from 'dns'; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100755 index 0000000..77cd807 --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,370 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses, and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the + * default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100755 index 0000000..fafe68a --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/domain.js) + */ +declare module 'domain' { + import EventEmitter = require('node:events'); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module 'node:domain' { + export * from 'domain'; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100755 index 0000000..b8283ac --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,641 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + } + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('events'); + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require('node:events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module 'node:events' { + import events = require('events'); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100755 index 0000000..75c53fb --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3872 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/fs.js) + */ +declare module 'fs' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = 'dir' | 'file' | 'junction'; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open(path: PathLike, flags: OpenMode | undefined, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open(path: PathLike, flags: OpenMode | undefined, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + export function read(fd: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: (curr: BigIntStats, prev: BigIntStats) => void + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: PathLike, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp(source: string | URL, destination: string | URL, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string | URL, destination: string | URL, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100755 index 0000000..9d0b5f1 --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1120 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module 'fs/promises' { + import { Abortable } from 'node:events'; + import { Stream } from 'node:stream'; + import { ReadableStream } from 'node:stream/web'; + import { + BigIntStats, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatOptions, + Stats, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from 'node:fs'; + + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed + * or closing. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. + * + * @since v17.0.0 + * @experimental + */ + readableWebStream(): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + } + + const constants: typeof fsConstants; + + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module 'node:fs/promises' { + export * from 'fs/promises'; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100755 index 0000000..da49994 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,294 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare var gc: undefined | (() => void); + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#region ArrayLike.at() +interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; +} +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end + +/** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ +declare function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, +): T; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/node_modules/@types/node/globals.global.d.ts b/node_modules/@types/node/globals.global.d.ts new file mode 100755 index 0000000..ef1198c --- /dev/null +++ b/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100755 index 0000000..cced16d --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,1452 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + 'accept-language'?: string | undefined; + 'accept-patch'?: string | undefined; + 'accept-ranges'?: string | undefined; + 'access-control-allow-credentials'?: string | undefined; + 'access-control-allow-headers'?: string | undefined; + 'access-control-allow-methods'?: string | undefined; + 'access-control-allow-origin'?: string | undefined; + 'access-control-expose-headers'?: string | undefined; + 'access-control-max-age'?: string | undefined; + 'access-control-request-headers'?: string | undefined; + 'access-control-request-method'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + 'alt-svc'?: string | undefined; + authorization?: string | undefined; + 'cache-control'?: string | undefined; + connection?: string | undefined; + 'content-disposition'?: string | undefined; + 'content-encoding'?: string | undefined; + 'content-language'?: string | undefined; + 'content-length'?: string | undefined; + 'content-location'?: string | undefined; + 'content-range'?: string | undefined; + 'content-type'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + 'if-match'?: string | undefined; + 'if-modified-since'?: string | undefined; + 'if-none-match'?: string | undefined; + 'if-unmodified-since'?: string | undefined; + 'last-modified'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + 'proxy-authenticate'?: string | undefined; + 'proxy-authorization'?: string | undefined; + 'public-key-pins'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + 'retry-after'?: string | undefined; + 'sec-websocket-accept'?: string | undefined; + 'sec-websocket-extensions'?: string | undefined; + 'sec-websocket-key'?: string | undefined; + 'sec-websocket-protocol'?: string | undefined; + 'sec-websocket-version'?: string | undefined; + 'set-cookie'?: string[] | undefined; + 'strict-transport-security'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + 'transfer-encoding'?: string | undefined; + upgrade?: string | undefined; + 'user-agent'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + 'www-authenticate'?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict {} + interface ClientRequestArgs { + signal?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + lookup?: LookupFunction | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * const http = require('http'); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * const http = require('http'); + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.getHeaders()); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo' | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module 'node:http' { + export * from 'http'; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100755 index 0000000..a394b2c --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2106 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http2.js) + */ +declare module 'http2' { + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; + export interface IncomingHttpStatusHeader { + ':status'?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: 'http:' | 'https:' | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} +declare module 'node:http2' { + export * from 'http2'; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100755 index 0000000..5b78a3f --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,401 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/https.js) + */ +declare module 'https' { + import { Duplex } from 'node:stream'; + import * as tls from 'node:tls'; + import * as http from 'node:http'; + import { URL } from 'node:url'; + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Duplex) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Duplex): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Duplex) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Duplex) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} +declare module 'node:https' { + export * from 'https'; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100755 index 0000000..f972978 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,132 @@ +// Type definitions for non-npm package Node.js 18.7 +// Project: https://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Piotr Błażejewicz +// Anna Henningsen +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// wafuwafu13 +// Matteo Collina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 3.7+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100755 index 0000000..a64ab6b --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2741 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100755 index 0000000..d83aec9 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module 'node:module' { + import module = require('module'); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100755 index 0000000..7fa4ac9 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,816 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/net.js) + */ +declare module 'net' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import * as dns from 'node:dns'; + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = 'opening' | 'open' | 'readOnly' | 'writeOnly' | 'closed'; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'timeout', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean; + emit(event: 'ready'): boolean; + emit(event: 'timeout'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'timeout', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'timeout', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + type IPVersion = 'ipv4' | 'ipv6'; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module 'node:net' { + export * from 'net'; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100755 index 0000000..cad5ecc --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,456 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): 'BE' | 'LE'; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module 'node:os' { + export * from 'os'; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100755 index 0000000..072c8ae --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,225 @@ +{ + "name": "@types/node", + "version": "18.7.5", + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft", + "githubUsername": "Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped", + "githubUsername": "DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno", + "githubUsername": "jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis", + "githubUsername": "alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya", + "githubUsername": "r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg", + "githubUsername": "btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89", + "githubUsername": "smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy", + "githubUsername": "touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas", + "githubUsername": "DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs", + "githubUsername": "eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK", + "githubUsername": "Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29", + "githubUsername": "hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin", + "githubUsername": "kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff", + "githubUsername": "ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude", + "githubUsername": "islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk", + "githubUsername": "mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1", + "githubUsername": "mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e", + "githubUsername": "n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin", + "githubUsername": "galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs", + "githubUsername": "parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon", + "githubUsername": "eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick", + "githubUsername": "SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH", + "githubUsername": "ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker", + "githubUsername": "WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3", + "githubUsername": "wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela", + "githubUsername": "samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein", + "githubUsername": "kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy", + "githubUsername": "bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar", + "githubUsername": "chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr", + "githubUsername": "trivikr" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny", + "githubUsername": "yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias", + "githubUsername": "qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax", + "githubUsername": "addaleax" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin", + "githubUsername": "victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys", + "githubUsername": "ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS", + "githubUsername": "NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU", + "githubUsername": "LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13", + "githubUsername": "wafuwafu13" + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "githubUsername": "mcollina" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "b3d2ce548d64952af2585c97148879dfa054b7a7ea087a095c93ddd158dbb37b", + "typeScriptVersion": "4.0" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100755 index 0000000..f8ee95f --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/path.js) + */ +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param ext optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module 'node:path' { + import path = require('path'); + export = path; +} +declare module 'node:path/posix' { + import path = require('path/posix'); + export = path; +} +declare module 'node:path/win32' { + import path = require('path/win32'); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100755 index 0000000..cf02a16 --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,610 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: 'mark'; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: 'measure'; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + } + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from other to this histogram. + * @since v17.4.0, v16.14.0 + * @param other Recordable Histogram to combine with + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100755 index 0000000..70598c0 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1482 @@ +declare module 'process' { + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + type Architecture = 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x64'; + type Signals = + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; + type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume the the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; + } + } + } + export = process; +} +declare module 'node:process' { + import process = require('process'); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100755 index 0000000..87ebbb9 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + */ +declare module 'punycode' { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module 'node:punycode' { + export * from 'punycode'; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100755 index 0000000..e694d8c --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `URLSearchParams` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module 'node:querystring' { + export * from 'querystring'; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100755 index 0000000..6ab64ac --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,653 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + import * as promises from 'node:readline/promises'; + + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'history', listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'history', listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'history', listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100755 index 0000000..8f9f06f --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module 'readline/promises' { + import { Interface as _Interface, ReadLineOptions, Completer, AsyncCompleter, Direction } from 'node:readline'; + import { Abortable } from 'node:events'; + + class Interface extends _Interface { + /** + * The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, + * then invokes the callback function passing the provided input as the first argument. + * + * When called, rl.question() will resume the input stream if it has been paused. + * + * If the readlinePromises.Interface was created with output set to null or undefined the query is not written. + * + * If the question is called after rl.close(), it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an AbortSignal to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * @since v17.0.0 + * @param query A statement or query to write to output, prepended to the prompt. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + class Readline { + /** + * @param stream A TTY stream. + */ + constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property, + * and emits a `'resize'` event on the `output`, if or when the columns ever change (`process.stdout` does this automatically when it is a TTY). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module 'node:readline/promises' { + export * from 'readline/promises'; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100755 index 0000000..be42ccc --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'node:readline'; + import { Context } from 'node:vm'; + import { InspectOptions } from 'node:util'; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'exit', listener: () => void): this; + addListener(event: 'reset', listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'exit'): boolean; + emit(event: 'reset', context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'exit', listener: () => void): this; + on(event: 'reset', listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'exit', listener: () => void): this; + once(event: 'reset', listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'exit', listener: () => void): this; + prependListener(event: 'reset', listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'exit', listener: () => void): this; + prependOnceListener(event: 'reset', listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module 'node:repl' { + export * from 'repl'; +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100755 index 0000000..d478f33 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1339 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; + import * as streamWeb from 'node:stream/web'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb(readableStream: streamWeb.ReadableStream, options?: Pick): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v18.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v8.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb(writableStream: streamWeb.WritableStream, options?: Pick): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v8.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit 'drain'. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from(src: Stream | Blob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | Promise | Object): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v17.4.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module 'node:stream' { + import stream = require('stream'); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100755 index 0000000..ce6c9bb --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,24 @@ +// Duplicates of interface in lib.dom.ts. +// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all" +// Which in turn causes tests to pass that shouldn't pass. +// +// This interface is not, and should not be, exported. +interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): NodeJS.ReadableStream; + text(): Promise; +} +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; +} +declare module 'node:stream/consumers' { + export * from 'stream/consumers'; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100755 index 0000000..b427073 --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100755 index 0000000..f9ef057 --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,330 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: 'bytes'; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new (stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new (): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new (): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new (transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new (): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new (underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new (stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new (): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new (init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new (init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: 'utf-8'; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new (): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new (label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100755 index 0000000..a585804 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `string_decoder` module provides an API for decoding `Buffer` objects into + * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/string_decoder.js) + */ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100755 index 0000000..9ba9512 --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,176 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/test.js) + */ +declare module 'node:test' { + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in the creation of a test point in the TAP output. + * + * The {@link TestContext} object passed to the fn argument can be used to perform actions + * related to the current test. Examples include skipping the test, adding additional TAP + * diagnostic information, or creating subtests. + * + * `test()` returns a {@link Promise} that resolves once the test completes. The return value + * can usually be discarded for top level tests. However, the return value from subtests should + * be used to prevent the parent test from finishing first and cancelling the subtest as shown + * in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + + /* + * @since v18.6.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function describe(name?: string, fn?: SuiteFn): void; + function describe(options?: TestOptions, fn?: SuiteFn): void; + function describe(fn?: SuiteFn): void; + + /* + * @since v18.6.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: ItFn): void; + function it(name?: string, fn?: ItFn): void; + function it(options?: TestOptions, fn?: ItFn): void; + function it(fn?: ItFn): void; + + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + + /** + * The type of a function under Suite. + * If the test uses callbacks, the callback function is passed as an argument + */ + type SuiteFn = (done: (result?: any) => void) => void; + + /** + * The type of a function under test. + * If the test uses callbacks, the callback function is passed as an argument + */ + type ItFn = (done: (result?: any) => void) => any; + + /** + * An instance of `TestContext` is passed to each test function in order to interact with the + * test runner. However, the `TestContext` constructor is not exposed as part of the API. + * @since v18.0.0 + */ + interface TestContext { + /** + * This function is used to write TAP diagnostics to the output. Any diagnostic information is + * included at the end of the test's results. This function does not return a value. + * @param message Message to be displayed as a TAP diagnostic. + * @since v18.0.0 + */ + diagnostic(message: string): void; + + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` + * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` + * command-line option, this function is a no-op. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v18.0.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * This function causes the test's output to indicate the test as skipped. If `message` is + * provided, it is included in the TAP output. Calling `skip()` does not terminate execution of + * the test function. This function does not return a value. + * @param message Optional skip message to be displayed in TAP output. + * @since v18.0.0 + */ + skip(message?: string): void; + + /** + * This function adds a `TODO` directive to the test's output. If `message` is provided, it is + * included in the TAP output. Calling `todo()` does not terminate execution of the test + * function. This function does not return a value. + * @param message Optional `TODO` message to be displayed in TAP output. + * @since v18.0.0 + */ + todo(message?: string): void; + + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + } + + interface TestOptions { + /** + * The number of tests that can be run at the same time. If unspecified, subtests inherit this + * value from their parent. + * @default 1 + */ + concurrency?: number; + + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean; + + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string; + + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string; + } + + export { test as default, test, describe, it }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100755 index 0000000..b26f3ce --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises'; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module 'node:timers' { + export * from 'timers'; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100755 index 0000000..fd77888 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100755 index 0000000..816766e --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1028 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + import * as stream from 'stream'; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom`options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +declare module 'node:tls' { + export * from 'tls'; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100755 index 0000000..d47aa93 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,171 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/trace_events.js) + */ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module 'node:trace_events' { + export * from 'trace_events'; +} diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100755 index 0000000..6473f8d --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tty.js) + */ +declare module 'tty' { + import * as net from 'node:net'; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'resize', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'resize'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'resize', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'resize', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'resize', listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module 'node:tty' { + export * from 'tty'; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100755 index 0000000..18362c8 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,897 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/url.js) + */ +declare module 'url' { + import { Blob } from 'node:buffer'; + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn’t registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | Record> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach(callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, thisArg?: TThis): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from 'url'; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer URL; + } + ? URL + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer URLSearchParams; + } + ? URLSearchParams + : typeof _URLSearchParams; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100755 index 0000000..a081325 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,1792 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(thousand, million, bigNumber, bigDecimal); + * // 1_000 1_000_000 123_456_789n 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + + /** + * Provides a high-level API for command-line argument parsing. Takes a + * specification for the expected arguments and returns a structured object + * with the parsed values and positionals. + * + * `config` provides arguments for parsing and configures the parser. It + * supports the following properties: + * + * - `args` The array of argument strings. **Default:** `process.argv` with + * `execPath` and `filename` removed. + * - `options` Arguments known to the parser. Keys of `options` are the long + * names of options and values are objects accepting the following properties: + * + * - `type` Type of argument, which must be either `boolean` (for options + * which do not take values) or `string` (for options which do). + * - `multiple` Whether this option can be provided multiple + * times. If `true`, all values will be collected in an array. If + * `false`, values for the option are last-wins. **Default:** `false`. + * - `short` A single character alias for the option. + * + * - `strict`: Whether an error should be thrown when unknown arguments + * are encountered, or when arguments are passed that do not match the + * `type` configured in `options`. **Default:** `true`. + * - `allowPositionals`: Whether this command accepts positional arguments. + * **Default:** `false` if `strict` is `true`, otherwise `true`. + * - `tokens`: Whether tokens {boolean} Return the parsed tokens. This is useful + * for extending the built-in behavior, from adding additional checks through + * to reprocessing the tokens in different ways. + * **Default:** `false`. + * + * @returns The parsed command line arguments: + * + * - `values` A mapping of parsed option names with their string + * or boolean values. + * - `positionals` Positional arguments. + * - `tokens` Detailed parse information (only if `tokens` was specified). + * + */ + export function parseArgs(config: T): ParsedResults; + + interface ParseArgsOptionConfig { + type: 'string' | 'boolean'; + short?: string; + multiple?: boolean; + } + + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + + export interface ParseArgsConfig { + strict?: boolean; + allowPositionals?: boolean; + tokens?: boolean; + options?: ParseArgsOptionsConfig; + args?: string[]; + } + + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true + ? IfTrue + : T extends false + ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false + ? IfFalse + : T extends true + ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T['strict'], + O['type'] extends 'string' ? string : O['type'] extends 'boolean' ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T['options'] extends ParseArgsOptionsConfig + ? { + -readonly [LongOption in keyof T['options']]: IfDefaultsFalse< + T['options'][LongOption]['multiple'], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T['strict'], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O['type'] extends 'string' + ? { + kind: 'option'; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O['type'] extends 'boolean' + ? { + kind: 'option'; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T['options'] = keyof T['options'], + > = K extends unknown + ? T['options'] extends ParseArgsOptionsConfig + ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T['strict'], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: 'option-terminator'; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T['tokens'], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: 'option'; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: 'option'; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: 'positional'; index: number; value: string } + | { kind: 'option-terminator'; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T + ? { + values: { [longOption: string]: undefined | string | boolean | Array }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; +} +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module 'node:util' { + export * from 'util'; +} +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100755 index 0000000..6685dc2 --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,396 @@ +/** + * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/v8.js) + */ +declare module 'v8' { + import { Readable } from 'node:stream'; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer’s internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; +} +declare module 'node:v8' { + export * from 'v8'; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100755 index 0000000..c96513a --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,509 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/vm.js) + */ +declare module 'vm' { + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + type MeasureMemoryMode = 'summary' | 'detailed'; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + context?: Context | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` + +``` + +### With browserify + +Engine.IO is a commonjs module, which means you can include it by using +`require` on the browser and package using [browserify](http://browserify.org/): + +1. install the client package + + ```bash + $ npm install engine.io-client + ``` + +1. write your app code + + ```js + const { Socket } = require('engine.io-client'); + const socket = new Socket('ws://localhost'); + socket.on('open', () => { + socket.on('message', (data) => {}); + socket.on('close', () => {}); + }); + ``` + +1. build your app bundle + + ```bash + $ browserify app.js > bundle.js + ``` + +1. include on your page + + ```html + + ``` + +### Sending and receiving binary + +```html + + +``` + +### Node.JS + +Add `engine.io-client` to your `package.json` and then: + +```js +const { Socket } = require('engine.io-client'); +const socket = new Socket('ws://localhost'); +socket.on('open', () => { + socket.on('message', (data) => {}); + socket.on('close', () => {}); +}); +``` + +### Node.js with certificates +```js +const opts = { + key: fs.readFileSync('test/fixtures/client.key'), + cert: fs.readFileSync('test/fixtures/client.crt'), + ca: fs.readFileSync('test/fixtures/ca.crt') +}; + +const { Socket } = require('engine.io-client'); +const socket = new Socket('ws://localhost', opts); +socket.on('open', () => { + socket.on('message', (data) => {}); + socket.on('close', () => {}); +}); +``` + +### Node.js with extraHeaders +```js +const opts = { + extraHeaders: { + 'X-Custom-Header-For-My-Project': 'my-secret-access-token', + 'Cookie': 'user_session=NI2JlCKF90aE0sJZD9ZzujtdsUqNYSBYxzlTsvdSUe35ZzdtVRGqYFr0kdGxbfc5gUOkR9RGp20GVKza; path=/; expires=Tue, 07-Apr-2015 18:18:08 GMT; secure; HttpOnly' + } +}; + +const { Socket } = require('engine.io-client'); +const socket = new Socket('ws://localhost', opts); +socket.on('open', () => { + socket.on('message', (data) => {}); + socket.on('close', () => {}); +}); +``` + +In the browser, the [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object does not support additional headers. +In case you want to add some headers as part of some authentication mechanism, you can use the `transportOptions` attribute. +Please note that in this case the headers won't be sent in the WebSocket upgrade request. + +```js +// WILL NOT WORK in the browser +const socket = new Socket('http://localhost', { + extraHeaders: { + 'X-Custom-Header-For-My-Project': 'will not be sent' + } +}); +// WILL NOT WORK +const socket = new Socket('http://localhost', { + transports: ['websocket'], // polling is disabled + transportOptions: { + polling: { + extraHeaders: { + 'X-Custom-Header-For-My-Project': 'will not be sent' + } + } + } +}); +// WILL WORK +const socket = new Socket('http://localhost', { + transports: ['polling', 'websocket'], + transportOptions: { + polling: { + extraHeaders: { + 'X-Custom-Header-For-My-Project': 'will be used' + } + } + } +}); +``` + +## Features + +- Lightweight +- Runs on browser and node.js seamlessly +- Transports are independent of `Engine` + - Easy to debug + - Easy to unit test +- Runs inside HTML5 WebWorker +- Can send and receive binary data + - Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer + in Node + - When XHR2 or WebSockets are used, binary is emitted directly. Otherwise + binary is encoded into base64 strings, and decoded when binary types are + supported. + - With browsers that don't support ArrayBuffer, an object { base64: true, + data: dataAsBase64String } is emitted on the `message` event. + +## API + +### Socket + +The client class. Mixes in [Emitter](http://github.com/component/emitter). +Exposed as `eio` in the browser standalone build. + +#### Properties + +- `protocol` _(Number)_: protocol revision number +- `binaryType` _(String)_ : can be set to 'arraybuffer' or 'blob' in browsers, + and `buffer` or `arraybuffer` in Node. Blob is only used in browser if it's + supported. + +#### Events + +- `open` + - Fired upon successful connection. +- `message` + - Fired when data is received from the server. + - **Arguments** + - `String` | `ArrayBuffer`: utf-8 encoded data or ArrayBuffer containing + binary data +- `close` + - Fired upon disconnection. In compliance with the WebSocket API spec, this event may be + fired even if the `open` event does not occur (i.e. due to connection error or `close()`). +- `error` + - Fired when an error occurs. +- `flush` + - Fired upon completing a buffer flush +- `drain` + - Fired after `drain` event of transport if writeBuffer is empty +- `upgradeError` + - Fired if an error occurs with a transport we're trying to upgrade to. +- `upgrade` + - Fired upon upgrade success, after the new transport is set +- `ping` + - Fired upon receiving a ping packet. +- `pong` + - Fired upon _flushing_ a pong packet (ie: actual packet write out) + +#### Methods + +- **constructor** + - Initializes the client + - **Parameters** + - `String` uri + - `Object`: optional, options object + - **Options** + - `agent` (`http.Agent`): `http.Agent` to use, defaults to `false` (NodeJS only) + - `upgrade` (`Boolean`): defaults to true, whether the client should try + to upgrade the transport from long-polling to something better. + - `forceBase64` (`Boolean`): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary. + - `withCredentials` (`Boolean`): defaults to `false`, whether to include credentials (cookies, authorization headers, TLS client certificates, etc.) with cross-origin XHR polling requests. + - `timestampRequests` (`Boolean`): whether to add the timestamp with each + transport request. Note: polling requests are always stamped unless this + option is explicitly set to `false` (`false`) + - `timestampParam` (`String`): timestamp parameter (`t`) + - `path` (`String`): path to connect to, default is `/engine.io` + - `transports` (`Array`): a list of transports to try (in order). + Defaults to `['polling', 'websocket']`. `Engine` + always attempts to connect directly with the first one, provided the + feature detection test for it passes. + - `transportOptions` (`Object`): hash of options, indexed by transport name, overriding the common options for the given transport + - `rememberUpgrade` (`Boolean`): defaults to false. + If true and if the previous websocket connection to the server succeeded, + the connection attempt will bypass the normal upgrade process and will initially + try websocket. A connection attempt following a transport error will use the + normal upgrade process. It is recommended you turn this on only when using + SSL/TLS connections, or if you know that your network does not block websockets. + - `pfx` (`String`|`Buffer`): Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + - `key` (`String`): Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + - `passphrase` (`String`): A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information. + - `cert` (`String`): Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information. + - `ca` (`String`|`Array`): An authority certificate or array of authority certificates to check the remote host against.. Can be used in Node.js client environment to manually specify certificate information. + - `ciphers` (`String`): A string describing the ciphers to use or exclude. Consult the [cipher format list](http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for details on the format. Can be used in Node.js client environment to manually specify certificate information. + - `rejectUnauthorized` (`Boolean`): If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information. + - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension + (see [ws module](https://github.com/einaros/ws) api docs). Set to `false` to disable. (`true`) + - `threshold` (`Number`): data is compressed only if the byte size is above this value. This option is ignored on the browser. (`1024`) + - `extraHeaders` (`Object`): Headers that will be passed for each request to the server (via xhr-polling and via websockets). These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment. + - `onlyBinaryUpgrades` (`Boolean`): whether transport upgrades should be restricted to transports supporting binary data (`false`) + - `forceNode` (`Boolean`): Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron) (`false`, NodeJS only) + - `localAddress` (`String`): the local IP address to connect to + - `autoUnref` (`Boolean`): whether the transport should be `unref`'d upon creation. This calls `unref` on the underlying timers and sockets so that the program is allowed to exit if they are the only timers/sockets in the event system (Node.js only) + - `useNativeTimers` (`Boolean`): Whether to always use the native timeouts. This allows the client to reconnect when the native timeout functions are overridden, such as when mock clocks are installed with [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers). + - **Polling-only options** + - `requestTimeout` (`Number`): Timeout for xhr-polling requests in milliseconds (`0`) + - **Websocket-only options** + - `protocols` (`Array`): a list of subprotocols (see [MDN reference](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Subprotocols)) + - `closeOnBeforeunload` (`Boolean`): whether to silently close the connection when the [`beforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) event is emitted in the browser (defaults to `true`) +- `send` + - Sends a message to the server + - **Parameters** + - `String` | `ArrayBuffer` | `ArrayBufferView` | `Blob`: data to send + - `Object`: optional, options object + - `Function`: optional, callback upon `drain` + - **Options** + - `compress` (`Boolean`): whether to compress sending data. This option is ignored and forced to be `true` on the browser. (`true`) +- `close` + - Disconnects the client. + +### Transport + +The transport class. Private. _Inherits from EventEmitter_. + +#### Events + +- `poll`: emitted by polling transports upon starting a new request +- `pollComplete`: emitted by polling transports upon completing a request +- `drain`: emitted by polling transports upon a buffer drain + +## Tests + +`engine.io-client` is used to test +[engine](http://github.com/socketio/engine.io). Running the `engine.io` +test suite ensures the client works and vice-versa. + +Browser tests are run using [zuul](https://github.com/defunctzombie/zuul). You can +run the tests locally using the following command. + +``` +./node_modules/.bin/zuul --local 8080 -- test/index.js +``` + +Additionally, `engine.io-client` has a standalone test suite you can run +with `make test` which will run node.js and browser tests. You must have zuul setup with +a saucelabs account. + +## Support + +The support channels for `engine.io-client` are the same as `socket.io`: + - irc.freenode.net **#socket.io** + - [Google Groups](http://groups.google.com/group/socket_io) + - [Website](http://socket.io) + +## Development + +To contribute patches, run tests or benchmarks, make sure to clone the +repository: + +```bash +git clone git://github.com/socketio/engine.io-client.git +``` + +Then: + +```bash +cd engine.io-client +npm install +``` + +See the `Tests` section above for how to run tests before submitting any patches. + +## License + +MIT - Copyright (c) 2014 Automattic, Inc. diff --git a/node_modules/engine.io-client/build/cjs/browser-entrypoint.js b/node_modules/engine.io-client/build/cjs/browser-entrypoint.js new file mode 100644 index 0000000..9b84dee --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/browser-entrypoint.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const socket_js_1 = require("./socket.js"); +exports.default = (uri, opts) => new socket_js_1.Socket(uri, opts); diff --git a/node_modules/engine.io-client/build/cjs/contrib/has-cors.js b/node_modules/engine.io-client/build/cjs/contrib/has-cors.js new file mode 100644 index 0000000..8221e27 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/contrib/has-cors.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasCORS = void 0; +// imported from https://github.com/component/has-cors +let value = false; +try { + value = typeof XMLHttpRequest !== 'undefined' && + 'withCredentials' in new XMLHttpRequest(); +} +catch (err) { + // if XMLHttp support is disabled in IE then it will throw + // when trying to create +} +exports.hasCORS = value; diff --git a/node_modules/engine.io-client/build/cjs/contrib/parseqs.js b/node_modules/engine.io-client/build/cjs/contrib/parseqs.js new file mode 100644 index 0000000..c2359d5 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/contrib/parseqs.js @@ -0,0 +1,39 @@ +"use strict"; +// imported from https://github.com/galkn/querystring +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decode = exports.encode = void 0; +function encode(obj) { + let str = ''; + for (let i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) + str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + return str; +} +exports.encode = encode; +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ +function decode(qs) { + let qry = {}; + let pairs = qs.split('&'); + for (let i = 0, l = pairs.length; i < l; i++) { + let pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + return qry; +} +exports.decode = decode; diff --git a/node_modules/engine.io-client/build/cjs/contrib/parseuri.js b/node_modules/engine.io-client/build/cjs/contrib/parseuri.js new file mode 100644 index 0000000..958e709 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/contrib/parseuri.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parse = void 0; +// imported from https://github.com/galkn/parseuri +/** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ +const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; +const parts = [ + 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' +]; +function parse(str) { + const src = str, b = str.indexOf('['), e = str.indexOf(']'); + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + let m = re.exec(str || ''), uri = {}, i = 14; + while (i--) { + uri[parts[i]] = m[i] || ''; + } + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + uri.pathNames = pathNames(uri, uri['path']); + uri.queryKey = queryKey(uri, uri['query']); + return uri; +} +exports.parse = parse; +function pathNames(obj, path) { + const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/"); + if (path.substr(0, 1) == '/' || path.length === 0) { + names.splice(0, 1); + } + if (path.substr(path.length - 1, 1) == '/') { + names.splice(names.length - 1, 1); + } + return names; +} +function queryKey(uri, query) { + const data = {}; + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { + if ($1) { + data[$1] = $2; + } + }); + return data; +} diff --git a/node_modules/engine.io-client/build/cjs/contrib/yeast.js b/node_modules/engine.io-client/build/cjs/contrib/yeast.js new file mode 100644 index 0000000..9357705 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/contrib/yeast.js @@ -0,0 +1,55 @@ +// imported from https://github.com/unshiftio/yeast +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.yeast = exports.decode = exports.encode = void 0; +const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {}; +let seed = 0, i = 0, prev; +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +function encode(num) { + let encoded = ''; + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + return encoded; +} +exports.encode = encode; +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +function decode(str) { + let decoded = 0; + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + return decoded; +} +exports.decode = decode; +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +function yeast() { + const now = encode(+new Date()); + if (now !== prev) + return seed = 0, prev = now; + return now + '.' + encode(seed++); +} +exports.yeast = yeast; +// +// Map each character to its index. +// +for (; i < length; i++) + map[alphabet[i]] = i; diff --git a/node_modules/engine.io-client/build/cjs/globalThis.browser.js b/node_modules/engine.io-client/build/cjs/globalThis.browser.js new file mode 100644 index 0000000..4e548de --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/globalThis.browser.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.globalThisShim = void 0; +exports.globalThisShim = (() => { + if (typeof self !== "undefined") { + return self; + } + else if (typeof window !== "undefined") { + return window; + } + else { + return Function("return this")(); + } +})(); diff --git a/node_modules/engine.io-client/build/cjs/globalThis.js b/node_modules/engine.io-client/build/cjs/globalThis.js new file mode 100644 index 0000000..23fd516 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/globalThis.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.globalThisShim = void 0; +exports.globalThisShim = global; diff --git a/node_modules/engine.io-client/build/cjs/index.js b/node_modules/engine.io-client/build/cjs/index.js new file mode 100644 index 0000000..6227a14 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/index.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parse = exports.installTimerFunctions = exports.transports = exports.Transport = exports.protocol = exports.Socket = void 0; +const socket_js_1 = require("./socket.js"); +Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } }); +exports.protocol = socket_js_1.Socket.protocol; +var transport_js_1 = require("./transport.js"); +Object.defineProperty(exports, "Transport", { enumerable: true, get: function () { return transport_js_1.Transport; } }); +var index_js_1 = require("./transports/index.js"); +Object.defineProperty(exports, "transports", { enumerable: true, get: function () { return index_js_1.transports; } }); +var util_js_1 = require("./util.js"); +Object.defineProperty(exports, "installTimerFunctions", { enumerable: true, get: function () { return util_js_1.installTimerFunctions; } }); +var parseuri_js_1 = require("./contrib/parseuri.js"); +Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parseuri_js_1.parse; } }); diff --git a/node_modules/engine.io-client/build/cjs/package.json b/node_modules/engine.io-client/build/cjs/package.json new file mode 100644 index 0000000..9cf26e4 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/package.json @@ -0,0 +1,10 @@ +{ + "name": "engine.io-client", + "type": "commonjs", + "browser": { + "ws": false, + "./transports/xmlhttprequest.js": "./transports/xmlhttprequest.browser.js", + "./transports/websocket-constructor.js": "./transports/websocket-constructor.browser.js", + "./globalThis.js": "./globalThis.browser.js" + } +} diff --git a/node_modules/engine.io-client/build/cjs/socket.js b/node_modules/engine.io-client/build/cjs/socket.js new file mode 100644 index 0000000..b7489df --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/socket.js @@ -0,0 +1,611 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Socket = void 0; +const index_js_1 = require("./transports/index.js"); +const util_js_1 = require("./util.js"); +const parseqs_js_1 = require("./contrib/parseqs.js"); +const parseuri_js_1 = require("./contrib/parseuri.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const component_emitter_1 = require("@socket.io/component-emitter"); +const engine_io_parser_1 = require("engine.io-parser"); +const debug = (0, debug_1.default)("engine.io-client:socket"); // debug() +class Socket extends component_emitter_1.Emitter { + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri, opts = {}) { + super(); + if (uri && "object" === typeof uri) { + opts = uri; + uri = null; + } + if (uri) { + uri = (0, parseuri_js_1.parse)(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) + opts.query = uri.query; + } + else if (opts.host) { + opts.hostname = (0, parseuri_js_1.parse)(opts.host).host; + } + (0, util_js_1.installTimerFunctions)(this, opts); + this.secure = + null != opts.secure + ? opts.secure + : typeof location !== "undefined" && "https:" === location.protocol; + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = this.secure ? "443" : "80"; + } + this.hostname = + opts.hostname || + (typeof location !== "undefined" ? location.hostname : "localhost"); + this.port = + opts.port || + (typeof location !== "undefined" && location.port + ? location.port + : this.secure + ? "443" + : "80"); + this.transports = opts.transports || ["polling", "websocket"]; + this.readyState = ""; + this.writeBuffer = []; + this.prevBufferLen = 0; + this.opts = Object.assign({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + this.opts.path = this.opts.path.replace(/\/$/, "") + "/"; + if (typeof this.opts.query === "string") { + this.opts.query = (0, parseqs_js_1.decode)(this.opts.query); + } + // set on handshake + this.id = null; + this.upgrades = null; + this.pingInterval = null; + this.pingTimeout = null; + // set on heartbeat + this.pingTimeoutTimer = null; + if (typeof addEventListener === "function") { + if (this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", () => { + if (this.transport) { + // silently close the transport + this.transport.removeAllListeners(); + this.transport.close(); + } + }, false); + } + if (this.hostname !== "localhost") { + this.offlineEventListener = () => { + this.onClose("transport close", { + description: "network connection lost" + }); + }; + addEventListener("offline", this.offlineEventListener, false); + } + } + this.open(); + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + createTransport(name) { + debug('creating transport "%s"', name); + const query = Object.assign({}, this.opts.query); + // append engine.io protocol identifier + query.EIO = engine_io_parser_1.protocol; + // transport name + query.transport = name; + // session id if we already have one + if (this.id) + query.sid = this.id; + const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, { + query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + debug("options: %j", opts); + return new index_js_1.transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + open() { + let transport; + if (this.opts.rememberUpgrade && + Socket.priorWebsocketSuccess && + this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } + else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(() => { + this.emitReserved("error", "No transports available"); + }, 0); + return; + } + else { + transport = this.transports[0]; + } + this.readyState = "opening"; + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } + catch (e) { + debug("error while creating transport: %s", e); + this.transports.shift(); + this.open(); + return; + } + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + setTransport(transport) { + debug("setting transport %s", transport.name); + if (this.transport) { + debug("clearing existing transport %s", this.transport.name); + this.transport.removeAllListeners(); + } + // set up transport + this.transport = transport; + // set up transport listeners + transport + .on("drain", this.onDrain.bind(this)) + .on("packet", this.onPacket.bind(this)) + .on("error", this.onError.bind(this)) + .on("close", reason => this.onClose("transport close", reason)); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + probe(name) { + debug('probing transport "%s"', name); + let transport = this.createTransport(name); + let failed = false; + Socket.priorWebsocketSuccess = false; + const onTransportOpen = () => { + if (failed) + return; + debug('probe transport "%s" opened', name); + transport.send([{ type: "ping", data: "probe" }]); + transport.once("packet", msg => { + if (failed) + return; + if ("pong" === msg.type && "probe" === msg.data) { + debug('probe transport "%s" pong', name); + this.upgrading = true; + this.emitReserved("upgrading", transport); + if (!transport) + return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + debug('pausing current transport "%s"', this.transport.name); + this.transport.pause(() => { + if (failed) + return; + if ("closed" === this.readyState) + return; + debug("changing transport and sending upgrade packet"); + cleanup(); + this.setTransport(transport); + transport.send([{ type: "upgrade" }]); + this.emitReserved("upgrade", transport); + transport = null; + this.upgrading = false; + this.flush(); + }); + } + else { + debug('probe transport "%s" failed', name); + const err = new Error("probe error"); + // @ts-ignore + err.transport = transport.name; + this.emitReserved("upgradeError", err); + } + }); + }; + function freezeTransport() { + if (failed) + return; + // Any callback called by transport should be ignored since now + failed = true; + cleanup(); + transport.close(); + transport = null; + } + // Handle any error that happens while probing + const onerror = err => { + const error = new Error("probe error: " + err); + // @ts-ignore + error.transport = transport.name; + freezeTransport(); + debug('probe transport "%s" failed because of error: %s', name, err); + this.emitReserved("upgradeError", error); + }; + function onTransportClose() { + onerror("transport closed"); + } + // When the socket is closed while we're probing + function onclose() { + onerror("socket closed"); + } + // When the socket is upgraded while we're probing + function onupgrade(to) { + if (transport && to.name !== transport.name) { + debug('"%s" works - aborting "%s"', to.name, transport.name); + freezeTransport(); + } + } + // Remove all listeners on the transport and on self + const cleanup = () => { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + this.off("close", onclose); + this.off("upgrading", onupgrade); + }; + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + onOpen() { + debug("socket open"); + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); + // we check for `readyState` in case an `open` + // listener already closed the socket + if ("open" === this.readyState && + this.opts.upgrade && + this.transport.pause) { + debug("starting upgrade probes"); + let i = 0; + const l = this.upgrades.length; + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + onPacket(packet) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + this.emitReserved("packet", packet); + // Socket is live - any packet counts + this.emitReserved("heartbeat"); + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + case "error": + const err = new Error("server error"); + // @ts-ignore + err.code = packet.data; + this.onError(err); + break; + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + else { + debug('packet received with socket readyState "%s"', this.readyState); + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.maxPayload = data.maxPayload; + this.onOpen(); + // In case open handler closes socket + if ("closed" === this.readyState) + return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + resetPingTimeout() { + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(() => { + this.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } + else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + flush() { + if ("closed" !== this.readyState && + this.transport.writable && + !this.upgrading && + this.writeBuffer.length) { + const packets = this.getWritablePackets(); + debug("flushing %d packets in socket", packets.length); + this.transport.send(packets); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = packets.length; + this.emitReserved("flush"); + } + } + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + getWritablePackets() { + const shouldCheckPayloadSize = this.maxPayload && + this.transport.name === "polling" && + this.writeBuffer.length > 1; + if (!shouldCheckPayloadSize) { + return this.writeBuffer; + } + let payloadSize = 1; // first packet type + for (let i = 0; i < this.writeBuffer.length; i++) { + const data = this.writeBuffer[i].data; + if (data) { + payloadSize += (0, util_js_1.byteLength)(data); + } + if (i > 0 && payloadSize > this.maxPayload) { + debug("only send %d out of %d packets", i, this.writeBuffer.length); + return this.writeBuffer.slice(0, i); + } + payloadSize += 2; // separator + packet type + } + debug("payload size is %d (max: %d)", payloadSize, this.maxPayload); + return this.writeBuffer; + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + if ("function" === typeof options) { + fn = options; + options = null; + } + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + options = options || {}; + options.compress = false !== options.compress; + const packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) + this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + close() { + const close = () => { + this.onClose("forced close"); + debug("socket closing - telling transport to close"); + this.transport.close(); + }; + const cleanupAndClose = () => { + this.off("upgrade", cleanupAndClose); + this.off("upgradeError", cleanupAndClose); + close(); + }; + const waitForUpgrade = () => { + // wait for upgrade to finish since we can't send packets while pausing a transport + this.once("upgrade", cleanupAndClose); + this.once("upgradeError", cleanupAndClose); + }; + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + if (this.writeBuffer.length) { + this.once("drain", () => { + if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + }); + } + else if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + } + return this; + } + /** + * Called upon transport error + * + * @api private + */ + onError(err) { + debug("socket error %j", err); + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + onClose(reason, description) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket close with reason: "%s"', reason); + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); + // stop event from firing again for transport + this.transport.removeAllListeners("close"); + // ensure transport won't stay open + this.transport.close(); + // ignore further transport communication + this.transport.removeAllListeners(); + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } + // set ready state + this.readyState = "closed"; + // clear session id + this.id = null; + // emit close event + this.emitReserved("close", reason, description); + // clean buffers after, so users can still + // grab the buffers on `close` event + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + filterUpgrades(upgrades) { + const filteredUpgrades = []; + let i = 0; + const j = upgrades.length; + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) + filteredUpgrades.push(upgrades[i]); + } + return filteredUpgrades; + } +} +exports.Socket = Socket; +Socket.protocol = engine_io_parser_1.protocol; diff --git a/node_modules/engine.io-client/build/cjs/transport.js b/node_modules/engine.io-client/build/cjs/transport.js new file mode 100644 index 0000000..f270154 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transport.js @@ -0,0 +1,126 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transport = void 0; +const engine_io_parser_1 = require("engine.io-parser"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const util_js_1 = require("./util.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = (0, debug_1.default)("engine.io-client:transport"); // debug() +class TransportError extends Error { + constructor(reason, description, context) { + super(reason); + this.description = description; + this.context = context; + this.type = "TransportError"; + } +} +class Transport extends component_emitter_1.Emitter { + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts) { + super(); + this.writable = false; + (0, util_js_1.installTimerFunctions)(this, opts); + this.opts = opts; + this.query = opts.query; + this.readyState = ""; + this.socket = opts.socket; + } + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + onError(reason, description, context) { + super.emitReserved("error", new TransportError(reason, description, context)); + return this; + } + /** + * Opens the transport. + * + * @api public + */ + open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + return this; + } + /** + * Closes the transport. + * + * @api public + */ + close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + else { + // this might happen if the transport was silently closed in the beforeunload event handler + debug("transport is not open, discarding packets"); + } + } + /** + * Called upon open + * + * @api protected + */ + onOpen() { + this.readyState = "open"; + this.writable = true; + super.emitReserved("open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + onData(data) { + const packet = (0, engine_io_parser_1.decodePacket)(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + onPacket(packet) { + super.emitReserved("packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + onClose(details) { + this.readyState = "closed"; + super.emitReserved("close", details); + } +} +exports.Transport = Transport; diff --git a/node_modules/engine.io-client/build/cjs/transports/index.js b/node_modules/engine.io-client/build/cjs/transports/index.js new file mode 100644 index 0000000..8a687a5 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.transports = void 0; +const polling_js_1 = require("./polling.js"); +const websocket_js_1 = require("./websocket.js"); +exports.transports = { + websocket: websocket_js_1.WS, + polling: polling_js_1.Polling +}; diff --git a/node_modules/engine.io-client/build/cjs/transports/polling.js b/node_modules/engine.io-client/build/cjs/transports/polling.js new file mode 100644 index 0000000..a672db2 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/polling.js @@ -0,0 +1,427 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Request = exports.Polling = void 0; +const transport_js_1 = require("../transport.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const yeast_js_1 = require("../contrib/yeast.js"); +const parseqs_js_1 = require("../contrib/parseqs.js"); +const engine_io_parser_1 = require("engine.io-parser"); +const xmlhttprequest_js_1 = require("./xmlhttprequest.js"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const util_js_1 = require("../util.js"); +const globalThis_js_1 = require("../globalThis.js"); +const debug = (0, debug_1.default)("engine.io-client:polling"); // debug() +function empty() { } +const hasXHR2 = (function () { + const xhr = new xmlhttprequest_js_1.XHR({ + xdomain: false + }); + return null != xhr.responseType; +})(); +class Polling extends transport_js_1.Transport { + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts) { + super(opts); + this.polling = false; + if (typeof location !== "undefined") { + const isSSL = "https:" === location.protocol; + let port = location.port; + // some user agents have empty `location.port` + if (!port) { + port = isSSL ? "443" : "80"; + } + this.xd = + (typeof location !== "undefined" && + opts.hostname !== location.hostname) || + port !== opts.port; + this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + const forceBase64 = opts && opts.forceBase64; + this.supportsBinary = hasXHR2 && !forceBase64; + } + /** + * Transport name. + */ + get name() { + return "polling"; + } + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause) { + this.readyState = "pausing"; + const pause = () => { + debug("paused"); + this.readyState = "paused"; + onPause(); + }; + if (this.polling || !this.writable) { + let total = 0; + if (this.polling) { + debug("we are currently polling - waiting to pause"); + total++; + this.once("pollComplete", function () { + debug("pre-pause polling complete"); + --total || pause(); + }); + } + if (!this.writable) { + debug("we are currently writing - waiting to pause"); + total++; + this.once("drain", function () { + debug("pre-pause writing complete"); + --total || pause(); + }); + } + } + else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + poll() { + debug("polling"); + this.polling = true; + this.doPoll(); + this.emitReserved("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data) { + debug("polling got data %s", data); + const callback = packet => { + // if its the first message we consider the transport open + if ("opening" === this.readyState && packet.type === "open") { + this.onOpen(); + } + // if its a close packet, we close the ongoing requests + if ("close" === packet.type) { + this.onClose({ description: "transport closed by the server" }); + return false; + } + // otherwise bypass onData and handle the message + this.onPacket(packet); + }; + // decode payload + (0, engine_io_parser_1.decodePayload)(data, this.socket.binaryType).forEach(callback); + // if an event did not trigger closing + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emitReserved("pollComplete"); + if ("open" === this.readyState) { + this.poll(); + } + else { + debug('ignoring poll - transport state "%s"', this.readyState); + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + doClose() { + const close = () => { + debug("writing close packet"); + this.write([{ type: "close" }]); + }; + if ("open" === this.readyState) { + debug("transport open - closing"); + close(); + } + else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + debug("transport not open - deferring close"); + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets) { + this.writable = false; + (0, engine_io_parser_1.encodePayload)(packets, data => { + this.doWrite(data, () => { + this.writable = true; + this.emitReserved("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "https" : "http"; + let port = ""; + // cache busting is forced + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = (0, yeast_js_1.yeast)(); + } + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } + // avoid port if default for schema + if (this.opts.port && + (("https" === schema && Number(this.opts.port) !== 443) || + ("http" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + const encodedQuery = (0, parseqs_js_1.encode)(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts = {}) { + Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts); + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data, fn) { + const req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", (xhrStatus, context) => { + this.onError("xhr post error", xhrStatus, context); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll() { + debug("xhr poll"); + const req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", (xhrStatus, context) => { + this.onError("xhr poll error", xhrStatus, context); + }); + this.pollXhr = req; + } +} +exports.Polling = Polling; +class Request extends component_emitter_1.Emitter { + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri, opts) { + super(); + (0, util_js_1.installTimerFunctions)(this, opts); + this.opts = opts; + this.method = opts.method || "GET"; + this.uri = uri; + this.async = false !== opts.async; + this.data = undefined !== opts.data ? opts.data : null; + this.create(); + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + create() { + const opts = (0, util_js_1.pick)(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + const xhr = (this.xhr = new xmlhttprequest_js_1.XHR(opts)); + try { + debug("xhr open %s: %s", this.method, this.uri); + xhr.open(this.method, this.uri, this.async); + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + for (let i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } + catch (e) { } + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } + catch (e) { } + } + try { + xhr.setRequestHeader("Accept", "*/*"); + } + catch (e) { } + // ie6 check + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + xhr.onreadystatechange = () => { + if (4 !== xhr.readyState) + return; + if (200 === xhr.status || 1223 === xhr.status) { + this.onLoad(); + } + else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + this.setTimeoutFn(() => { + this.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + debug("xhr data %s", this.data); + xhr.send(this.data); + } + catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(() => { + this.onError(e); + }, 0); + return; + } + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon error. + * + * @api private + */ + onError(err) { + this.emitReserved("error", err, this.xhr); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + this.xhr.onreadystatechange = empty; + if (fromError) { + try { + this.xhr.abort(); + } + catch (e) { } + } + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + onLoad() { + const data = this.xhr.responseText; + if (data !== null) { + this.emitReserved("data", data); + this.emitReserved("success"); + this.cleanup(); + } + } + /** + * Aborts the request. + * + * @api public + */ + abort() { + this.cleanup(); + } +} +exports.Request = Request; +Request.requestsCount = 0; +Request.requests = {}; +/** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ +if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } + else if (typeof addEventListener === "function") { + const terminationEvent = "onpagehide" in globalThis_js_1.globalThisShim ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } +} +function unloadHandler() { + for (let i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } +} diff --git a/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.browser.js b/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.browser.js new file mode 100644 index 0000000..61fae2a --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.browser.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultBinaryType = exports.usingBrowserWebSocket = exports.WebSocket = exports.nextTick = void 0; +const globalThis_js_1 = require("../globalThis.js"); +exports.nextTick = (() => { + const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + if (isPromiseAvailable) { + return cb => Promise.resolve().then(cb); + } + else { + return (cb, setTimeoutFn) => setTimeoutFn(cb, 0); + } +})(); +exports.WebSocket = globalThis_js_1.globalThisShim.WebSocket || globalThis_js_1.globalThisShim.MozWebSocket; +exports.usingBrowserWebSocket = true; +exports.defaultBinaryType = "arraybuffer"; diff --git a/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.js b/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.js new file mode 100644 index 0000000..6ebda11 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/websocket-constructor.js @@ -0,0 +1,11 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.nextTick = exports.defaultBinaryType = exports.usingBrowserWebSocket = exports.WebSocket = void 0; +const ws_1 = __importDefault(require("ws")); +exports.WebSocket = ws_1.default; +exports.usingBrowserWebSocket = false; +exports.defaultBinaryType = "nodebuffer"; +exports.nextTick = process.nextTick; diff --git a/node_modules/engine.io-client/build/cjs/transports/websocket.js b/node_modules/engine.io-client/build/cjs/transports/websocket.js new file mode 100644 index 0000000..13df6d4 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/websocket.js @@ -0,0 +1,198 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WS = void 0; +const transport_js_1 = require("../transport.js"); +const parseqs_js_1 = require("../contrib/parseqs.js"); +const yeast_js_1 = require("../contrib/yeast.js"); +const util_js_1 = require("../util.js"); +const websocket_constructor_js_1 = require("./websocket-constructor.js"); +const debug_1 = __importDefault(require("debug")); // debug() +const engine_io_parser_1 = require("engine.io-parser"); +const debug = (0, debug_1.default)("engine.io-client:websocket"); // debug() +// detect ReactNative environment +const isReactNative = typeof navigator !== "undefined" && + typeof navigator.product === "string" && + navigator.product.toLowerCase() === "reactnative"; +class WS extends transport_js_1.Transport { + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts) { + super(opts); + this.supportsBinary = !opts.forceBase64; + } + /** + * Transport name. + * + * @api public + */ + get name() { + return "websocket"; + } + /** + * Opens socket. + * + * @api private + */ + doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + const uri = this.uri(); + const protocols = this.opts.protocols; + // React Native only supports the 'headers' option, and will print a warning if anything else is passed + const opts = isReactNative + ? {} + : (0, util_js_1.pick)(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + try { + this.ws = + websocket_constructor_js_1.usingBrowserWebSocket && !isReactNative + ? protocols + ? new websocket_constructor_js_1.WebSocket(uri, protocols) + : new websocket_constructor_js_1.WebSocket(uri) + : new websocket_constructor_js_1.WebSocket(uri, protocols, opts); + } + catch (err) { + return this.emitReserved("error", err); + } + this.ws.binaryType = this.socket.binaryType || websocket_constructor_js_1.defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners() { + this.ws.onopen = () => { + if (this.opts.autoUnref) { + this.ws._socket.unref(); + } + this.onOpen(); + }; + this.ws.onclose = closeEvent => this.onClose({ + description: "websocket connection closed", + context: closeEvent + }); + this.ws.onmessage = ev => this.onData(ev.data); + this.ws.onerror = e => this.onError("websocket error", e); + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets) { + this.writable = false; + // encodePacket efficient as it uses WS framing + // no need for encodePayload + for (let i = 0; i < packets.length; i++) { + const packet = packets[i]; + const lastPacket = i === packets.length - 1; + (0, engine_io_parser_1.encodePacket)(packet, this.supportsBinary, data => { + // always create a new object (GH-437) + const opts = {}; + if (!websocket_constructor_js_1.usingBrowserWebSocket) { + if (packet.options) { + opts.compress = packet.options.compress; + } + if (this.opts.perMessageDeflate) { + const len = + // @ts-ignore + "string" === typeof data ? Buffer.byteLength(data) : data.length; + if (len < this.opts.perMessageDeflate.threshold) { + opts.compress = false; + } + } + } + // Sometimes the websocket has already been closed but the browser didn't + // have a chance of informing us about it yet, in that case send will + // throw an error + try { + if (websocket_constructor_js_1.usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + this.ws.send(data); + } + else { + this.ws.send(data, opts); + } + } + catch (e) { + debug("websocket closed before onclose event"); + } + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + (0, websocket_constructor_js_1.nextTick)(() => { + this.writable = true; + this.emitReserved("drain"); + }, this.setTimeoutFn); + } + }); + } + } + /** + * Closes socket. + * + * @api private + */ + doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "wss" : "ws"; + let port = ""; + // avoid port if default for schema + if (this.opts.port && + (("wss" === schema && Number(this.opts.port) !== 443) || + ("ws" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + // append timestamp to URI + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = (0, yeast_js_1.yeast)(); + } + // communicate binary support capabilities + if (!this.supportsBinary) { + query.b64 = 1; + } + const encodedQuery = (0, parseqs_js_1.encode)(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check() { + return !!websocket_constructor_js_1.WebSocket; + } +} +exports.WS = WS; diff --git a/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.browser.js b/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.browser.js new file mode 100644 index 0000000..ceae587 --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.browser.js @@ -0,0 +1,23 @@ +"use strict"; +// browser shim for xmlhttprequest module +Object.defineProperty(exports, "__esModule", { value: true }); +exports.XHR = void 0; +const has_cors_js_1 = require("../contrib/has-cors.js"); +const globalThis_js_1 = require("../globalThis.js"); +function XHR(opts) { + const xdomain = opts.xdomain; + // XMLHttpRequest can be disabled on IE + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || has_cors_js_1.hasCORS)) { + return new XMLHttpRequest(); + } + } + catch (e) { } + if (!xdomain) { + try { + return new globalThis_js_1.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } + catch (e) { } + } +} +exports.XHR = XHR; diff --git a/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.js b/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.js new file mode 100644 index 0000000..a490e0a --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/transports/xmlhttprequest.js @@ -0,0 +1,28 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.XHR = void 0; +const XMLHttpRequestModule = __importStar(require("xmlhttprequest-ssl")); +exports.XHR = XMLHttpRequestModule.default || XMLHttpRequestModule; diff --git a/node_modules/engine.io-client/build/cjs/util.js b/node_modules/engine.io-client/build/cjs/util.js new file mode 100644 index 0000000..7e49abe --- /dev/null +++ b/node_modules/engine.io-client/build/cjs/util.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.byteLength = exports.installTimerFunctions = exports.pick = void 0; +const globalThis_js_1 = require("./globalThis.js"); +function pick(obj, ...attr) { + return attr.reduce((acc, k) => { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + return acc; + }, {}); +} +exports.pick = pick; +// Keep a reference to the real timeout functions so they can be used when overridden +const NATIVE_SET_TIMEOUT = setTimeout; +const NATIVE_CLEAR_TIMEOUT = clearTimeout; +function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis_js_1.globalThisShim); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis_js_1.globalThisShim); + } + else { + obj.setTimeoutFn = setTimeout.bind(globalThis_js_1.globalThisShim); + obj.clearTimeoutFn = clearTimeout.bind(globalThis_js_1.globalThisShim); + } +} +exports.installTimerFunctions = installTimerFunctions; +// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) +const BASE64_OVERHEAD = 1.33; +// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 +function byteLength(obj) { + if (typeof obj === "string") { + return utf8Length(obj); + } + // arraybuffer or blob + return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); +} +exports.byteLength = byteLength; +function utf8Length(str) { + let c = 0, length = 0; + for (let i = 0, l = str.length; i < l; i++) { + c = str.charCodeAt(i); + if (c < 0x80) { + length += 1; + } + else if (c < 0x800) { + length += 2; + } + else if (c < 0xd800 || c >= 0xe000) { + length += 3; + } + else { + i++; + length += 4; + } + } + return length; +} diff --git a/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.d.ts b/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.d.ts new file mode 100644 index 0000000..66bff7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.d.ts @@ -0,0 +1,3 @@ +import { Socket } from "./socket.js"; +declare const _default: (uri: any, opts: any) => Socket; +export default _default; diff --git a/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.js b/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.js new file mode 100644 index 0000000..ca62e3e --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/browser-entrypoint.js @@ -0,0 +1,2 @@ +import { Socket } from "./socket.js"; +export default (uri, opts) => new Socket(uri, opts); diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.d.ts b/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.d.ts new file mode 100644 index 0000000..346b0a5 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.d.ts @@ -0,0 +1 @@ +export declare const hasCORS: boolean; diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.js b/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.js new file mode 100644 index 0000000..4e3edf4 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/has-cors.js @@ -0,0 +1,11 @@ +// imported from https://github.com/component/has-cors +let value = false; +try { + value = typeof XMLHttpRequest !== 'undefined' && + 'withCredentials' in new XMLHttpRequest(); +} +catch (err) { + // if XMLHttp support is disabled in IE then it will throw + // when trying to create +} +export const hasCORS = value; diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.d.ts b/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.d.ts new file mode 100644 index 0000000..528aab1 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.d.ts @@ -0,0 +1,15 @@ +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ +export declare function encode(obj: any): string; +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ +export declare function decode(qs: any): {}; diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.js b/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.js new file mode 100644 index 0000000..aea0f7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/parseqs.js @@ -0,0 +1,34 @@ +// imported from https://github.com/galkn/querystring +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ +export function encode(obj) { + let str = ''; + for (let i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) + str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + return str; +} +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ +export function decode(qs) { + let qry = {}; + let pairs = qs.split('&'); + for (let i = 0, l = pairs.length; i < l; i++) { + let pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + return qry; +} diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.d.ts b/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.d.ts new file mode 100644 index 0000000..31a3ca7 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.d.ts @@ -0,0 +1 @@ +export declare function parse(str: any): any; diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.js b/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.js new file mode 100644 index 0000000..f68f863 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/parseuri.js @@ -0,0 +1,49 @@ +// imported from https://github.com/galkn/parseuri +/** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ +const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; +const parts = [ + 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' +]; +export function parse(str) { + const src = str, b = str.indexOf('['), e = str.indexOf(']'); + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + let m = re.exec(str || ''), uri = {}, i = 14; + while (i--) { + uri[parts[i]] = m[i] || ''; + } + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + uri.pathNames = pathNames(uri, uri['path']); + uri.queryKey = queryKey(uri, uri['query']); + return uri; +} +function pathNames(obj, path) { + const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/"); + if (path.substr(0, 1) == '/' || path.length === 0) { + names.splice(0, 1); + } + if (path.substr(path.length - 1, 1) == '/') { + names.splice(names.length - 1, 1); + } + return names; +} +function queryKey(uri, query) { + const data = {}; + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { + if ($1) { + data[$1] = $2; + } + }); + return data; +} diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/yeast.d.ts b/node_modules/engine.io-client/build/esm-debug/contrib/yeast.d.ts new file mode 100644 index 0000000..29b5b45 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/yeast.d.ts @@ -0,0 +1,23 @@ +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +export declare function encode(num: any): string; +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +export declare function decode(str: any): number; +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +export declare function yeast(): string; diff --git a/node_modules/engine.io-client/build/esm-debug/contrib/yeast.js b/node_modules/engine.io-client/build/esm-debug/contrib/yeast.js new file mode 100644 index 0000000..e091032 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/contrib/yeast.js @@ -0,0 +1,50 @@ +// imported from https://github.com/unshiftio/yeast +'use strict'; +const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {}; +let seed = 0, i = 0, prev; +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +export function encode(num) { + let encoded = ''; + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + return encoded; +} +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +export function decode(str) { + let decoded = 0; + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + return decoded; +} +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +export function yeast() { + const now = encode(+new Date()); + if (now !== prev) + return seed = 0, prev = now; + return now + '.' + encode(seed++); +} +// +// Map each character to its index. +// +for (; i < length; i++) + map[alphabet[i]] = i; diff --git a/node_modules/engine.io-client/build/esm-debug/globalThis.browser.d.ts b/node_modules/engine.io-client/build/esm-debug/globalThis.browser.d.ts new file mode 100644 index 0000000..28d0a7c --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/globalThis.browser.d.ts @@ -0,0 +1 @@ +export declare const globalThisShim: any; diff --git a/node_modules/engine.io-client/build/esm-debug/globalThis.browser.js b/node_modules/engine.io-client/build/esm-debug/globalThis.browser.js new file mode 100644 index 0000000..ac26899 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/globalThis.browser.js @@ -0,0 +1,11 @@ +export const globalThisShim = (() => { + if (typeof self !== "undefined") { + return self; + } + else if (typeof window !== "undefined") { + return window; + } + else { + return Function("return this")(); + } +})(); diff --git a/node_modules/engine.io-client/build/esm-debug/globalThis.d.ts b/node_modules/engine.io-client/build/esm-debug/globalThis.d.ts new file mode 100644 index 0000000..4b9b90f --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/globalThis.d.ts @@ -0,0 +1 @@ +export declare const globalThisShim: typeof globalThis; diff --git a/node_modules/engine.io-client/build/esm-debug/globalThis.js b/node_modules/engine.io-client/build/esm-debug/globalThis.js new file mode 100644 index 0000000..27a616b --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/globalThis.js @@ -0,0 +1 @@ +export const globalThisShim = global; diff --git a/node_modules/engine.io-client/build/esm-debug/index.d.ts b/node_modules/engine.io-client/build/esm-debug/index.d.ts new file mode 100644 index 0000000..dca50e8 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/index.d.ts @@ -0,0 +1,8 @@ +import { Socket } from "./socket.js"; +export { Socket }; +export { SocketOptions } from "./socket.js"; +export declare const protocol: number; +export { Transport } from "./transport.js"; +export { transports } from "./transports/index.js"; +export { installTimerFunctions } from "./util.js"; +export { parse } from "./contrib/parseuri.js"; diff --git a/node_modules/engine.io-client/build/esm-debug/index.js b/node_modules/engine.io-client/build/esm-debug/index.js new file mode 100644 index 0000000..7394127 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/index.js @@ -0,0 +1,7 @@ +import { Socket } from "./socket.js"; +export { Socket }; +export const protocol = Socket.protocol; +export { Transport } from "./transport.js"; +export { transports } from "./transports/index.js"; +export { installTimerFunctions } from "./util.js"; +export { parse } from "./contrib/parseuri.js"; diff --git a/node_modules/engine.io-client/build/esm-debug/package.json b/node_modules/engine.io-client/build/esm-debug/package.json new file mode 100644 index 0000000..89498b3 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/package.json @@ -0,0 +1,10 @@ +{ + "name": "engine.io-client", + "type": "module", + "browser": { + "ws": false, + "./transports/xmlhttprequest.js": "./transports/xmlhttprequest.browser.js", + "./transports/websocket-constructor.js": "./transports/websocket-constructor.browser.js", + "./globalThis.js": "./globalThis.browser.js" + } +} diff --git a/node_modules/engine.io-client/build/esm-debug/socket.d.ts b/node_modules/engine.io-client/build/esm-debug/socket.d.ts new file mode 100644 index 0000000..d2999cf --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/socket.d.ts @@ -0,0 +1,352 @@ +import { Emitter } from "@socket.io/component-emitter"; +import { CloseDetails } from "./transport.js"; +export interface SocketOptions { + /** + * The host that we're connecting to. Set from the URI passed when connecting + */ + host: string; + /** + * The hostname for our connection. Set from the URI passed when connecting + */ + hostname: string; + /** + * If this is a secure connection. Set from the URI passed when connecting + */ + secure: boolean; + /** + * The port for our connection. Set from the URI passed when connecting + */ + port: string | number; + /** + * Any query parameters in our uri. Set from the URI passed when connecting + */ + query: { + [key: string]: any; + }; + /** + * `http.Agent` to use, defaults to `false` (NodeJS only) + */ + agent: string | boolean; + /** + * Whether the client should try to upgrade the transport from + * long-polling to something better. + * @default true + */ + upgrade: boolean; + /** + * Forces base 64 encoding for polling transport even when XHR2 + * responseType is available and WebSocket even if the used standard + * supports binary. + */ + forceBase64: boolean; + /** + * The param name to use as our timestamp key + * @default 't' + */ + timestampParam: string; + /** + * Whether to add the timestamp with each transport request. Note: this + * is ignored if the browser is IE or Android, in which case requests + * are always stamped + * @default false + */ + timestampRequests: boolean; + /** + * A list of transports to try (in order). Engine.io always attempts to + * connect directly with the first one, provided the feature detection test + * for it passes. + * @default ['polling','websocket'] + */ + transports: string[]; + /** + * The port the policy server listens on + * @default 843 + */ + policyPost: number; + /** + * If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will + * initially try websocket. A connection attempt following a transport error + * will use the normal upgrade process. It is recommended you turn this on + * only when using SSL/TLS connections, or if you know that your network does + * not block websockets. + * @default false + */ + rememberUpgrade: boolean; + /** + * Are we only interested in transports that support binary? + */ + onlyBinaryUpgrades: boolean; + /** + * Timeout for xhr-polling requests in milliseconds (0) (only for polling transport) + */ + requestTimeout: number; + /** + * Transport options for Node.js client (headers etc) + */ + transportOptions: Object; + /** + * (SSL) Certificate, Private key and CA certificates to use for SSL. + * Can be used in Node.js client environment to manually specify + * certificate information. + */ + pfx: string; + /** + * (SSL) Private key to use for SSL. Can be used in Node.js client + * environment to manually specify certificate information. + */ + key: string; + /** + * (SSL) A string or passphrase for the private key or pfx. Can be + * used in Node.js client environment to manually specify certificate + * information. + */ + passphrase: string; + /** + * (SSL) Public x509 certificate to use. Can be used in Node.js client + * environment to manually specify certificate information. + */ + cert: string; + /** + * (SSL) An authority certificate or array of authority certificates to + * check the remote host against.. Can be used in Node.js client + * environment to manually specify certificate information. + */ + ca: string | string[]; + /** + * (SSL) A string describing the ciphers to use or exclude. Consult the + * [cipher format list] + * (http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for + * details on the format.. Can be used in Node.js client environment to + * manually specify certificate information. + */ + ciphers: string; + /** + * (SSL) If true, the server certificate is verified against the list of + * supplied CAs. An 'error' event is emitted if verification fails. + * Verification happens at the connection level, before the HTTP request + * is sent. Can be used in Node.js client environment to manually specify + * certificate information. + */ + rejectUnauthorized: boolean; + /** + * Headers that will be passed for each request to the server (via xhr-polling and via websockets). + * These values then can be used during handshake or for special proxies. + */ + extraHeaders?: { + [header: string]: string; + }; + /** + * Whether to include credentials (cookies, authorization headers, TLS + * client certificates, etc.) with cross-origin XHR polling requests + * @default false + */ + withCredentials: boolean; + /** + * Whether to automatically close the connection whenever the beforeunload event is received. + * @default true + */ + closeOnBeforeunload: boolean; + /** + * Whether to always use the native timeouts. This allows the client to + * reconnect when the native timeout functions are overridden, such as when + * mock clocks are installed. + * @default false + */ + useNativeTimers: boolean; + /** + * weather we should unref the reconnect timer when it is + * create automatically + * @default false + */ + autoUnref: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. + * @default false + */ + perMessageDeflate: { + threshold: number; + }; + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/engine.io' + */ + path: string; + /** + * Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, + * so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to + * be able to handle different types of interactions depending on the specified protocol) + * @default [] + */ + protocols: string | string[]; +} +interface SocketReservedEvents { + open: () => void; + handshake: (data: any) => void; + packet: (packet: any) => void; + packetCreate: (packet: any) => void; + data: (data: any) => void; + message: (data: any) => void; + drain: () => void; + flush: () => void; + heartbeat: () => void; + ping: () => void; + pong: () => void; + error: (err: string | Error) => void; + upgrading: (transport: any) => void; + upgrade: (transport: any) => void; + upgradeError: (err: Error) => void; + close: (reason: string, description?: CloseDetails | Error) => void; +} +export declare class Socket extends Emitter<{}, {}, SocketReservedEvents> { + id: string; + transport: any; + binaryType: string; + private readyState; + private writeBuffer; + private prevBufferLen; + private upgrades; + private pingInterval; + private pingTimeout; + private pingTimeoutTimer; + private setTimeoutFn; + private clearTimeoutFn; + private offlineEventListener; + private upgrading; + private maxPayload?; + private readonly opts; + private readonly secure; + private readonly hostname; + private readonly port; + private readonly transports; + static priorWebsocketSuccess: boolean; + static protocol: number; + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri: any, opts?: Partial); + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + private createTransport; + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + private open; + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + private setTransport; + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + private probe; + /** + * Called when connection is deemed open. + * + * @api private + */ + private onOpen; + /** + * Handles a packet. + * + * @api private + */ + private onPacket; + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + private onHandshake; + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + private resetPingTimeout; + /** + * Called on `drain` event + * + * @api private + */ + private onDrain; + /** + * Flush write buffers. + * + * @api private + */ + private flush; + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + private getWritablePackets; + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg: any, options: any, fn?: any): this; + send(msg: any, options: any, fn?: any): this; + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + private sendPacket; + /** + * Closes the connection. + * + * @api public + */ + close(): this; + /** + * Called upon transport error + * + * @api private + */ + private onError; + /** + * Called upon transport close. + * + * @api private + */ + private onClose; + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + private filterUpgrades; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm-debug/socket.js b/node_modules/engine.io-client/build/esm-debug/socket.js new file mode 100644 index 0000000..65cb986 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/socket.js @@ -0,0 +1,604 @@ +import { transports } from "./transports/index.js"; +import { installTimerFunctions, byteLength } from "./util.js"; +import { decode } from "./contrib/parseqs.js"; +import { parse } from "./contrib/parseuri.js"; +import debugModule from "debug"; // debug() +import { Emitter } from "@socket.io/component-emitter"; +import { protocol } from "engine.io-parser"; +const debug = debugModule("engine.io-client:socket"); // debug() +export class Socket extends Emitter { + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri, opts = {}) { + super(); + if (uri && "object" === typeof uri) { + opts = uri; + uri = null; + } + if (uri) { + uri = parse(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) + opts.query = uri.query; + } + else if (opts.host) { + opts.hostname = parse(opts.host).host; + } + installTimerFunctions(this, opts); + this.secure = + null != opts.secure + ? opts.secure + : typeof location !== "undefined" && "https:" === location.protocol; + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = this.secure ? "443" : "80"; + } + this.hostname = + opts.hostname || + (typeof location !== "undefined" ? location.hostname : "localhost"); + this.port = + opts.port || + (typeof location !== "undefined" && location.port + ? location.port + : this.secure + ? "443" + : "80"); + this.transports = opts.transports || ["polling", "websocket"]; + this.readyState = ""; + this.writeBuffer = []; + this.prevBufferLen = 0; + this.opts = Object.assign({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + this.opts.path = this.opts.path.replace(/\/$/, "") + "/"; + if (typeof this.opts.query === "string") { + this.opts.query = decode(this.opts.query); + } + // set on handshake + this.id = null; + this.upgrades = null; + this.pingInterval = null; + this.pingTimeout = null; + // set on heartbeat + this.pingTimeoutTimer = null; + if (typeof addEventListener === "function") { + if (this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", () => { + if (this.transport) { + // silently close the transport + this.transport.removeAllListeners(); + this.transport.close(); + } + }, false); + } + if (this.hostname !== "localhost") { + this.offlineEventListener = () => { + this.onClose("transport close", { + description: "network connection lost" + }); + }; + addEventListener("offline", this.offlineEventListener, false); + } + } + this.open(); + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + createTransport(name) { + debug('creating transport "%s"', name); + const query = Object.assign({}, this.opts.query); + // append engine.io protocol identifier + query.EIO = protocol; + // transport name + query.transport = name; + // session id if we already have one + if (this.id) + query.sid = this.id; + const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, { + query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + debug("options: %j", opts); + return new transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + open() { + let transport; + if (this.opts.rememberUpgrade && + Socket.priorWebsocketSuccess && + this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } + else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(() => { + this.emitReserved("error", "No transports available"); + }, 0); + return; + } + else { + transport = this.transports[0]; + } + this.readyState = "opening"; + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } + catch (e) { + debug("error while creating transport: %s", e); + this.transports.shift(); + this.open(); + return; + } + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + setTransport(transport) { + debug("setting transport %s", transport.name); + if (this.transport) { + debug("clearing existing transport %s", this.transport.name); + this.transport.removeAllListeners(); + } + // set up transport + this.transport = transport; + // set up transport listeners + transport + .on("drain", this.onDrain.bind(this)) + .on("packet", this.onPacket.bind(this)) + .on("error", this.onError.bind(this)) + .on("close", reason => this.onClose("transport close", reason)); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + probe(name) { + debug('probing transport "%s"', name); + let transport = this.createTransport(name); + let failed = false; + Socket.priorWebsocketSuccess = false; + const onTransportOpen = () => { + if (failed) + return; + debug('probe transport "%s" opened', name); + transport.send([{ type: "ping", data: "probe" }]); + transport.once("packet", msg => { + if (failed) + return; + if ("pong" === msg.type && "probe" === msg.data) { + debug('probe transport "%s" pong', name); + this.upgrading = true; + this.emitReserved("upgrading", transport); + if (!transport) + return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + debug('pausing current transport "%s"', this.transport.name); + this.transport.pause(() => { + if (failed) + return; + if ("closed" === this.readyState) + return; + debug("changing transport and sending upgrade packet"); + cleanup(); + this.setTransport(transport); + transport.send([{ type: "upgrade" }]); + this.emitReserved("upgrade", transport); + transport = null; + this.upgrading = false; + this.flush(); + }); + } + else { + debug('probe transport "%s" failed', name); + const err = new Error("probe error"); + // @ts-ignore + err.transport = transport.name; + this.emitReserved("upgradeError", err); + } + }); + }; + function freezeTransport() { + if (failed) + return; + // Any callback called by transport should be ignored since now + failed = true; + cleanup(); + transport.close(); + transport = null; + } + // Handle any error that happens while probing + const onerror = err => { + const error = new Error("probe error: " + err); + // @ts-ignore + error.transport = transport.name; + freezeTransport(); + debug('probe transport "%s" failed because of error: %s', name, err); + this.emitReserved("upgradeError", error); + }; + function onTransportClose() { + onerror("transport closed"); + } + // When the socket is closed while we're probing + function onclose() { + onerror("socket closed"); + } + // When the socket is upgraded while we're probing + function onupgrade(to) { + if (transport && to.name !== transport.name) { + debug('"%s" works - aborting "%s"', to.name, transport.name); + freezeTransport(); + } + } + // Remove all listeners on the transport and on self + const cleanup = () => { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + this.off("close", onclose); + this.off("upgrading", onupgrade); + }; + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + onOpen() { + debug("socket open"); + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); + // we check for `readyState` in case an `open` + // listener already closed the socket + if ("open" === this.readyState && + this.opts.upgrade && + this.transport.pause) { + debug("starting upgrade probes"); + let i = 0; + const l = this.upgrades.length; + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + onPacket(packet) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + this.emitReserved("packet", packet); + // Socket is live - any packet counts + this.emitReserved("heartbeat"); + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + case "error": + const err = new Error("server error"); + // @ts-ignore + err.code = packet.data; + this.onError(err); + break; + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + else { + debug('packet received with socket readyState "%s"', this.readyState); + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.maxPayload = data.maxPayload; + this.onOpen(); + // In case open handler closes socket + if ("closed" === this.readyState) + return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + resetPingTimeout() { + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(() => { + this.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } + else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + flush() { + if ("closed" !== this.readyState && + this.transport.writable && + !this.upgrading && + this.writeBuffer.length) { + const packets = this.getWritablePackets(); + debug("flushing %d packets in socket", packets.length); + this.transport.send(packets); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = packets.length; + this.emitReserved("flush"); + } + } + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + getWritablePackets() { + const shouldCheckPayloadSize = this.maxPayload && + this.transport.name === "polling" && + this.writeBuffer.length > 1; + if (!shouldCheckPayloadSize) { + return this.writeBuffer; + } + let payloadSize = 1; // first packet type + for (let i = 0; i < this.writeBuffer.length; i++) { + const data = this.writeBuffer[i].data; + if (data) { + payloadSize += byteLength(data); + } + if (i > 0 && payloadSize > this.maxPayload) { + debug("only send %d out of %d packets", i, this.writeBuffer.length); + return this.writeBuffer.slice(0, i); + } + payloadSize += 2; // separator + packet type + } + debug("payload size is %d (max: %d)", payloadSize, this.maxPayload); + return this.writeBuffer; + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + if ("function" === typeof options) { + fn = options; + options = null; + } + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + options = options || {}; + options.compress = false !== options.compress; + const packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) + this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + close() { + const close = () => { + this.onClose("forced close"); + debug("socket closing - telling transport to close"); + this.transport.close(); + }; + const cleanupAndClose = () => { + this.off("upgrade", cleanupAndClose); + this.off("upgradeError", cleanupAndClose); + close(); + }; + const waitForUpgrade = () => { + // wait for upgrade to finish since we can't send packets while pausing a transport + this.once("upgrade", cleanupAndClose); + this.once("upgradeError", cleanupAndClose); + }; + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + if (this.writeBuffer.length) { + this.once("drain", () => { + if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + }); + } + else if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + } + return this; + } + /** + * Called upon transport error + * + * @api private + */ + onError(err) { + debug("socket error %j", err); + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + onClose(reason, description) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + debug('socket close with reason: "%s"', reason); + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); + // stop event from firing again for transport + this.transport.removeAllListeners("close"); + // ensure transport won't stay open + this.transport.close(); + // ignore further transport communication + this.transport.removeAllListeners(); + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } + // set ready state + this.readyState = "closed"; + // clear session id + this.id = null; + // emit close event + this.emitReserved("close", reason, description); + // clean buffers after, so users can still + // grab the buffers on `close` event + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + filterUpgrades(upgrades) { + const filteredUpgrades = []; + let i = 0; + const j = upgrades.length; + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) + filteredUpgrades.push(upgrades[i]); + } + return filteredUpgrades; + } +} +Socket.protocol = protocol; diff --git a/node_modules/engine.io-client/build/esm-debug/transport.d.ts b/node_modules/engine.io-client/build/esm-debug/transport.d.ts new file mode 100644 index 0000000..b919100 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transport.d.ts @@ -0,0 +1,96 @@ +import { Packet, RawData } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +import { SocketOptions } from "./socket.js"; +declare class TransportError extends Error { + readonly description: any; + readonly context: any; + readonly type = "TransportError"; + constructor(reason: string, description: any, context: any); +} +export interface CloseDetails { + description: string; + context?: CloseEvent | XMLHttpRequest; +} +interface TransportReservedEvents { + open: () => void; + error: (err: TransportError) => void; + packet: (packet: Packet) => void; + close: (details?: CloseDetails) => void; + poll: () => void; + pollComplete: () => void; + drain: () => void; +} +export declare abstract class Transport extends Emitter<{}, {}, TransportReservedEvents> { + protected opts: SocketOptions; + protected supportsBinary: boolean; + protected query: object; + protected readyState: string; + protected writable: boolean; + protected socket: any; + protected setTimeoutFn: typeof setTimeout; + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts: any); + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + protected onError(reason: string, description: any, context?: any): this; + /** + * Opens the transport. + * + * @api public + */ + private open; + /** + * Closes the transport. + * + * @api public + */ + close(): this; + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets: any): void; + /** + * Called upon open + * + * @api protected + */ + protected onOpen(): void; + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + protected onData(data: RawData): void; + /** + * Called with a decoded packet. + * + * @api protected + */ + protected onPacket(packet: Packet): void; + /** + * Called upon close. + * + * @api protected + */ + protected onClose(details?: CloseDetails): void; + protected abstract doOpen(): any; + protected abstract doClose(): any; + protected abstract write(packets: any): any; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm-debug/transport.js b/node_modules/engine.io-client/build/esm-debug/transport.js new file mode 100644 index 0000000..d9ff558 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transport.js @@ -0,0 +1,119 @@ +import { decodePacket } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +import { installTimerFunctions } from "./util.js"; +import debugModule from "debug"; // debug() +const debug = debugModule("engine.io-client:transport"); // debug() +class TransportError extends Error { + constructor(reason, description, context) { + super(reason); + this.description = description; + this.context = context; + this.type = "TransportError"; + } +} +export class Transport extends Emitter { + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts) { + super(); + this.writable = false; + installTimerFunctions(this, opts); + this.opts = opts; + this.query = opts.query; + this.readyState = ""; + this.socket = opts.socket; + } + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + onError(reason, description, context) { + super.emitReserved("error", new TransportError(reason, description, context)); + return this; + } + /** + * Opens the transport. + * + * @api public + */ + open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + return this; + } + /** + * Closes the transport. + * + * @api public + */ + close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + else { + // this might happen if the transport was silently closed in the beforeunload event handler + debug("transport is not open, discarding packets"); + } + } + /** + * Called upon open + * + * @api protected + */ + onOpen() { + this.readyState = "open"; + this.writable = true; + super.emitReserved("open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + onData(data) { + const packet = decodePacket(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + onPacket(packet) { + super.emitReserved("packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + onClose(details) { + this.readyState = "closed"; + super.emitReserved("close", details); + } +} diff --git a/node_modules/engine.io-client/build/esm-debug/transports/index.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/index.d.ts new file mode 100644 index 0000000..8a89404 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/index.d.ts @@ -0,0 +1,6 @@ +import { Polling } from "./polling.js"; +import { WS } from "./websocket.js"; +export declare const transports: { + websocket: typeof WS; + polling: typeof Polling; +}; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/index.js b/node_modules/engine.io-client/build/esm-debug/transports/index.js new file mode 100644 index 0000000..31fc7fa --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/index.js @@ -0,0 +1,6 @@ +import { Polling } from "./polling.js"; +import { WS } from "./websocket.js"; +export const transports = { + websocket: WS, + polling: Polling +}; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/polling.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/polling.d.ts new file mode 100644 index 0000000..2b47956 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/polling.d.ts @@ -0,0 +1,142 @@ +import { Transport } from "../transport.js"; +import { RawData } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +export declare class Polling extends Transport { + private readonly xd; + private readonly xs; + private polling; + private pollXhr; + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts: any); + /** + * Transport name. + */ + get name(): string; + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen(): void; + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause: any): void; + /** + * Starts polling cycle. + * + * @api public + */ + poll(): void; + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data: any): void; + /** + * For polling, send a close packet. + * + * @api private + */ + doClose(): void; + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets: any): void; + /** + * Generates uri for connection. + * + * @api private + */ + uri(): string; + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts?: {}): Request; + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data: any, fn: any): void; + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll(): void; +} +interface RequestReservedEvents { + success: () => void; + data: (data: RawData) => void; + error: (err: number | Error, context: XMLHttpRequest) => void; +} +export declare class Request extends Emitter<{}, {}, RequestReservedEvents> { + private readonly opts; + private readonly method; + private readonly uri; + private readonly async; + private readonly data; + private xhr; + private setTimeoutFn; + private index; + static requestsCount: number; + static requests: {}; + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri: any, opts: any); + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + private create; + /** + * Called upon error. + * + * @api private + */ + private onError; + /** + * Cleans up house. + * + * @api private + */ + private cleanup; + /** + * Called upon load. + * + * @api private + */ + private onLoad; + /** + * Aborts the request. + * + * @api public + */ + abort(): void; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/polling.js b/node_modules/engine.io-client/build/esm-debug/transports/polling.js new file mode 100644 index 0000000..a39e4fe --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/polling.js @@ -0,0 +1,419 @@ +import { Transport } from "../transport.js"; +import debugModule from "debug"; // debug() +import { yeast } from "../contrib/yeast.js"; +import { encode } from "../contrib/parseqs.js"; +import { encodePayload, decodePayload } from "engine.io-parser"; +import { XHR as XMLHttpRequest } from "./xmlhttprequest.js"; +import { Emitter } from "@socket.io/component-emitter"; +import { installTimerFunctions, pick } from "../util.js"; +import { globalThisShim as globalThis } from "../globalThis.js"; +const debug = debugModule("engine.io-client:polling"); // debug() +function empty() { } +const hasXHR2 = (function () { + const xhr = new XMLHttpRequest({ + xdomain: false + }); + return null != xhr.responseType; +})(); +export class Polling extends Transport { + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts) { + super(opts); + this.polling = false; + if (typeof location !== "undefined") { + const isSSL = "https:" === location.protocol; + let port = location.port; + // some user agents have empty `location.port` + if (!port) { + port = isSSL ? "443" : "80"; + } + this.xd = + (typeof location !== "undefined" && + opts.hostname !== location.hostname) || + port !== opts.port; + this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + const forceBase64 = opts && opts.forceBase64; + this.supportsBinary = hasXHR2 && !forceBase64; + } + /** + * Transport name. + */ + get name() { + return "polling"; + } + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause) { + this.readyState = "pausing"; + const pause = () => { + debug("paused"); + this.readyState = "paused"; + onPause(); + }; + if (this.polling || !this.writable) { + let total = 0; + if (this.polling) { + debug("we are currently polling - waiting to pause"); + total++; + this.once("pollComplete", function () { + debug("pre-pause polling complete"); + --total || pause(); + }); + } + if (!this.writable) { + debug("we are currently writing - waiting to pause"); + total++; + this.once("drain", function () { + debug("pre-pause writing complete"); + --total || pause(); + }); + } + } + else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + poll() { + debug("polling"); + this.polling = true; + this.doPoll(); + this.emitReserved("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data) { + debug("polling got data %s", data); + const callback = packet => { + // if its the first message we consider the transport open + if ("opening" === this.readyState && packet.type === "open") { + this.onOpen(); + } + // if its a close packet, we close the ongoing requests + if ("close" === packet.type) { + this.onClose({ description: "transport closed by the server" }); + return false; + } + // otherwise bypass onData and handle the message + this.onPacket(packet); + }; + // decode payload + decodePayload(data, this.socket.binaryType).forEach(callback); + // if an event did not trigger closing + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emitReserved("pollComplete"); + if ("open" === this.readyState) { + this.poll(); + } + else { + debug('ignoring poll - transport state "%s"', this.readyState); + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + doClose() { + const close = () => { + debug("writing close packet"); + this.write([{ type: "close" }]); + }; + if ("open" === this.readyState) { + debug("transport open - closing"); + close(); + } + else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + debug("transport not open - deferring close"); + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets) { + this.writable = false; + encodePayload(packets, data => { + this.doWrite(data, () => { + this.writable = true; + this.emitReserved("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "https" : "http"; + let port = ""; + // cache busting is forced + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } + // avoid port if default for schema + if (this.opts.port && + (("https" === schema && Number(this.opts.port) !== 443) || + ("http" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + const encodedQuery = encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts = {}) { + Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts); + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data, fn) { + const req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", (xhrStatus, context) => { + this.onError("xhr post error", xhrStatus, context); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll() { + debug("xhr poll"); + const req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", (xhrStatus, context) => { + this.onError("xhr poll error", xhrStatus, context); + }); + this.pollXhr = req; + } +} +export class Request extends Emitter { + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri, opts) { + super(); + installTimerFunctions(this, opts); + this.opts = opts; + this.method = opts.method || "GET"; + this.uri = uri; + this.async = false !== opts.async; + this.data = undefined !== opts.data ? opts.data : null; + this.create(); + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + create() { + const opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + const xhr = (this.xhr = new XMLHttpRequest(opts)); + try { + debug("xhr open %s: %s", this.method, this.uri); + xhr.open(this.method, this.uri, this.async); + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + for (let i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } + catch (e) { } + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } + catch (e) { } + } + try { + xhr.setRequestHeader("Accept", "*/*"); + } + catch (e) { } + // ie6 check + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + xhr.onreadystatechange = () => { + if (4 !== xhr.readyState) + return; + if (200 === xhr.status || 1223 === xhr.status) { + this.onLoad(); + } + else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + this.setTimeoutFn(() => { + this.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + debug("xhr data %s", this.data); + xhr.send(this.data); + } + catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(() => { + this.onError(e); + }, 0); + return; + } + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon error. + * + * @api private + */ + onError(err) { + this.emitReserved("error", err, this.xhr); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + this.xhr.onreadystatechange = empty; + if (fromError) { + try { + this.xhr.abort(); + } + catch (e) { } + } + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + onLoad() { + const data = this.xhr.responseText; + if (data !== null) { + this.emitReserved("data", data); + this.emitReserved("success"); + this.cleanup(); + } + } + /** + * Aborts the request. + * + * @api public + */ + abort() { + this.cleanup(); + } +} +Request.requestsCount = 0; +Request.requests = {}; +/** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ +if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } + else if (typeof addEventListener === "function") { + const terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } +} +function unloadHandler() { + for (let i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } +} diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.d.ts new file mode 100644 index 0000000..4f1b60e --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.d.ts @@ -0,0 +1,4 @@ +export declare const nextTick: (cb: any, setTimeoutFn: any) => any; +export declare const WebSocket: any; +export declare const usingBrowserWebSocket = true; +export declare const defaultBinaryType = "arraybuffer"; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.js b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.js new file mode 100644 index 0000000..e49bf1c --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.browser.js @@ -0,0 +1,13 @@ +import { globalThisShim as globalThis } from "../globalThis.js"; +export const nextTick = (() => { + const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + if (isPromiseAvailable) { + return cb => Promise.resolve().then(cb); + } + else { + return (cb, setTimeoutFn) => setTimeoutFn(cb, 0); + } +})(); +export const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket; +export const usingBrowserWebSocket = true; +export const defaultBinaryType = "arraybuffer"; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.d.ts new file mode 100644 index 0000000..5509500 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.d.ts @@ -0,0 +1,4 @@ +export declare const WebSocket: any; +export declare const usingBrowserWebSocket = false; +export declare const defaultBinaryType = "nodebuffer"; +export declare const nextTick: (callback: Function, ...args: any[]) => void; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.js b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.js new file mode 100644 index 0000000..fd0f46e --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket-constructor.js @@ -0,0 +1,5 @@ +import ws from "ws"; +export const WebSocket = ws; +export const usingBrowserWebSocket = false; +export const defaultBinaryType = "nodebuffer"; +export const nextTick = process.nextTick; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/websocket.d.ts new file mode 100644 index 0000000..837f47a --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket.d.ts @@ -0,0 +1,55 @@ +import { Transport } from "../transport.js"; +export declare class WS extends Transport { + private ws; + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts: any); + /** + * Transport name. + * + * @api public + */ + get name(): string; + /** + * Opens socket. + * + * @api private + */ + doOpen(): this; + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners(): void; + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets: any): void; + /** + * Closes socket. + * + * @api private + */ + doClose(): void; + /** + * Generates uri for connection. + * + * @api private + */ + uri(): string; + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check(): boolean; +} diff --git a/node_modules/engine.io-client/build/esm-debug/transports/websocket.js b/node_modules/engine.io-client/build/esm-debug/transports/websocket.js new file mode 100644 index 0000000..4bd4482 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/websocket.js @@ -0,0 +1,191 @@ +import { Transport } from "../transport.js"; +import { encode } from "../contrib/parseqs.js"; +import { yeast } from "../contrib/yeast.js"; +import { pick } from "../util.js"; +import { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from "./websocket-constructor.js"; +import debugModule from "debug"; // debug() +import { encodePacket } from "engine.io-parser"; +const debug = debugModule("engine.io-client:websocket"); // debug() +// detect ReactNative environment +const isReactNative = typeof navigator !== "undefined" && + typeof navigator.product === "string" && + navigator.product.toLowerCase() === "reactnative"; +export class WS extends Transport { + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts) { + super(opts); + this.supportsBinary = !opts.forceBase64; + } + /** + * Transport name. + * + * @api public + */ + get name() { + return "websocket"; + } + /** + * Opens socket. + * + * @api private + */ + doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + const uri = this.uri(); + const protocols = this.opts.protocols; + // React Native only supports the 'headers' option, and will print a warning if anything else is passed + const opts = isReactNative + ? {} + : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + try { + this.ws = + usingBrowserWebSocket && !isReactNative + ? protocols + ? new WebSocket(uri, protocols) + : new WebSocket(uri) + : new WebSocket(uri, protocols, opts); + } + catch (err) { + return this.emitReserved("error", err); + } + this.ws.binaryType = this.socket.binaryType || defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners() { + this.ws.onopen = () => { + if (this.opts.autoUnref) { + this.ws._socket.unref(); + } + this.onOpen(); + }; + this.ws.onclose = closeEvent => this.onClose({ + description: "websocket connection closed", + context: closeEvent + }); + this.ws.onmessage = ev => this.onData(ev.data); + this.ws.onerror = e => this.onError("websocket error", e); + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets) { + this.writable = false; + // encodePacket efficient as it uses WS framing + // no need for encodePayload + for (let i = 0; i < packets.length; i++) { + const packet = packets[i]; + const lastPacket = i === packets.length - 1; + encodePacket(packet, this.supportsBinary, data => { + // always create a new object (GH-437) + const opts = {}; + if (!usingBrowserWebSocket) { + if (packet.options) { + opts.compress = packet.options.compress; + } + if (this.opts.perMessageDeflate) { + const len = + // @ts-ignore + "string" === typeof data ? Buffer.byteLength(data) : data.length; + if (len < this.opts.perMessageDeflate.threshold) { + opts.compress = false; + } + } + } + // Sometimes the websocket has already been closed but the browser didn't + // have a chance of informing us about it yet, in that case send will + // throw an error + try { + if (usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + this.ws.send(data); + } + else { + this.ws.send(data, opts); + } + } + catch (e) { + debug("websocket closed before onclose event"); + } + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + nextTick(() => { + this.writable = true; + this.emitReserved("drain"); + }, this.setTimeoutFn); + } + }); + } + } + /** + * Closes socket. + * + * @api private + */ + doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "wss" : "ws"; + let port = ""; + // avoid port if default for schema + if (this.opts.port && + (("wss" === schema && Number(this.opts.port) !== 443) || + ("ws" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + // append timestamp to URI + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + // communicate binary support capabilities + if (!this.supportsBinary) { + query.b64 = 1; + } + const encodedQuery = encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check() { + return !!WebSocket; + } +} diff --git a/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.d.ts new file mode 100644 index 0000000..69c00e2 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.d.ts @@ -0,0 +1 @@ +export declare function XHR(opts: any): any; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.js b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.js new file mode 100644 index 0000000..70c3b1a --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.browser.js @@ -0,0 +1,19 @@ +// browser shim for xmlhttprequest module +import { hasCORS } from "../contrib/has-cors.js"; +import { globalThisShim as globalThis } from "../globalThis.js"; +export function XHR(opts) { + const xdomain = opts.xdomain; + // XMLHttpRequest can be disabled on IE + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { + return new XMLHttpRequest(); + } + } + catch (e) { } + if (!xdomain) { + try { + return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } + catch (e) { } + } +} diff --git a/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.d.ts b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.d.ts new file mode 100644 index 0000000..40ca535 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.d.ts @@ -0,0 +1 @@ +export declare const XHR: any; diff --git a/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.js b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.js new file mode 100644 index 0000000..1f66624 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/transports/xmlhttprequest.js @@ -0,0 +1,2 @@ +import * as XMLHttpRequestModule from "xmlhttprequest-ssl"; +export const XHR = XMLHttpRequestModule.default || XMLHttpRequestModule; diff --git a/node_modules/engine.io-client/build/esm-debug/util.d.ts b/node_modules/engine.io-client/build/esm-debug/util.d.ts new file mode 100644 index 0000000..5921b7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/util.d.ts @@ -0,0 +1,3 @@ +export declare function pick(obj: any, ...attr: any[]): any; +export declare function installTimerFunctions(obj: any, opts: any): void; +export declare function byteLength(obj: any): number; diff --git a/node_modules/engine.io-client/build/esm-debug/util.js b/node_modules/engine.io-client/build/esm-debug/util.js new file mode 100644 index 0000000..335c317 --- /dev/null +++ b/node_modules/engine.io-client/build/esm-debug/util.js @@ -0,0 +1,52 @@ +import { globalThisShim as globalThis } from "./globalThis.js"; +export function pick(obj, ...attr) { + return attr.reduce((acc, k) => { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + return acc; + }, {}); +} +// Keep a reference to the real timeout functions so they can be used when overridden +const NATIVE_SET_TIMEOUT = setTimeout; +const NATIVE_CLEAR_TIMEOUT = clearTimeout; +export function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis); + } + else { + obj.setTimeoutFn = setTimeout.bind(globalThis); + obj.clearTimeoutFn = clearTimeout.bind(globalThis); + } +} +// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) +const BASE64_OVERHEAD = 1.33; +// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 +export function byteLength(obj) { + if (typeof obj === "string") { + return utf8Length(obj); + } + // arraybuffer or blob + return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); +} +function utf8Length(str) { + let c = 0, length = 0; + for (let i = 0, l = str.length; i < l; i++) { + c = str.charCodeAt(i); + if (c < 0x80) { + length += 1; + } + else if (c < 0x800) { + length += 2; + } + else if (c < 0xd800 || c >= 0xe000) { + length += 3; + } + else { + i++; + length += 4; + } + } + return length; +} diff --git a/node_modules/engine.io-client/build/esm/browser-entrypoint.d.ts b/node_modules/engine.io-client/build/esm/browser-entrypoint.d.ts new file mode 100644 index 0000000..66bff7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm/browser-entrypoint.d.ts @@ -0,0 +1,3 @@ +import { Socket } from "./socket.js"; +declare const _default: (uri: any, opts: any) => Socket; +export default _default; diff --git a/node_modules/engine.io-client/build/esm/browser-entrypoint.js b/node_modules/engine.io-client/build/esm/browser-entrypoint.js new file mode 100644 index 0000000..ca62e3e --- /dev/null +++ b/node_modules/engine.io-client/build/esm/browser-entrypoint.js @@ -0,0 +1,2 @@ +import { Socket } from "./socket.js"; +export default (uri, opts) => new Socket(uri, opts); diff --git a/node_modules/engine.io-client/build/esm/contrib/has-cors.d.ts b/node_modules/engine.io-client/build/esm/contrib/has-cors.d.ts new file mode 100644 index 0000000..346b0a5 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/has-cors.d.ts @@ -0,0 +1 @@ +export declare const hasCORS: boolean; diff --git a/node_modules/engine.io-client/build/esm/contrib/has-cors.js b/node_modules/engine.io-client/build/esm/contrib/has-cors.js new file mode 100644 index 0000000..4e3edf4 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/has-cors.js @@ -0,0 +1,11 @@ +// imported from https://github.com/component/has-cors +let value = false; +try { + value = typeof XMLHttpRequest !== 'undefined' && + 'withCredentials' in new XMLHttpRequest(); +} +catch (err) { + // if XMLHttp support is disabled in IE then it will throw + // when trying to create +} +export const hasCORS = value; diff --git a/node_modules/engine.io-client/build/esm/contrib/parseqs.d.ts b/node_modules/engine.io-client/build/esm/contrib/parseqs.d.ts new file mode 100644 index 0000000..528aab1 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/parseqs.d.ts @@ -0,0 +1,15 @@ +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ +export declare function encode(obj: any): string; +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ +export declare function decode(qs: any): {}; diff --git a/node_modules/engine.io-client/build/esm/contrib/parseqs.js b/node_modules/engine.io-client/build/esm/contrib/parseqs.js new file mode 100644 index 0000000..aea0f7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/parseqs.js @@ -0,0 +1,34 @@ +// imported from https://github.com/galkn/querystring +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ +export function encode(obj) { + let str = ''; + for (let i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) + str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + return str; +} +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ +export function decode(qs) { + let qry = {}; + let pairs = qs.split('&'); + for (let i = 0, l = pairs.length; i < l; i++) { + let pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + return qry; +} diff --git a/node_modules/engine.io-client/build/esm/contrib/parseuri.d.ts b/node_modules/engine.io-client/build/esm/contrib/parseuri.d.ts new file mode 100644 index 0000000..31a3ca7 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/parseuri.d.ts @@ -0,0 +1 @@ +export declare function parse(str: any): any; diff --git a/node_modules/engine.io-client/build/esm/contrib/parseuri.js b/node_modules/engine.io-client/build/esm/contrib/parseuri.js new file mode 100644 index 0000000..f68f863 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/parseuri.js @@ -0,0 +1,49 @@ +// imported from https://github.com/galkn/parseuri +/** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ +const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; +const parts = [ + 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' +]; +export function parse(str) { + const src = str, b = str.indexOf('['), e = str.indexOf(']'); + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + let m = re.exec(str || ''), uri = {}, i = 14; + while (i--) { + uri[parts[i]] = m[i] || ''; + } + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + uri.pathNames = pathNames(uri, uri['path']); + uri.queryKey = queryKey(uri, uri['query']); + return uri; +} +function pathNames(obj, path) { + const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/"); + if (path.substr(0, 1) == '/' || path.length === 0) { + names.splice(0, 1); + } + if (path.substr(path.length - 1, 1) == '/') { + names.splice(names.length - 1, 1); + } + return names; +} +function queryKey(uri, query) { + const data = {}; + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { + if ($1) { + data[$1] = $2; + } + }); + return data; +} diff --git a/node_modules/engine.io-client/build/esm/contrib/yeast.d.ts b/node_modules/engine.io-client/build/esm/contrib/yeast.d.ts new file mode 100644 index 0000000..29b5b45 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/yeast.d.ts @@ -0,0 +1,23 @@ +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +export declare function encode(num: any): string; +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +export declare function decode(str: any): number; +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +export declare function yeast(): string; diff --git a/node_modules/engine.io-client/build/esm/contrib/yeast.js b/node_modules/engine.io-client/build/esm/contrib/yeast.js new file mode 100644 index 0000000..e091032 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/contrib/yeast.js @@ -0,0 +1,50 @@ +// imported from https://github.com/unshiftio/yeast +'use strict'; +const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {}; +let seed = 0, i = 0, prev; +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +export function encode(num) { + let encoded = ''; + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + return encoded; +} +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +export function decode(str) { + let decoded = 0; + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + return decoded; +} +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +export function yeast() { + const now = encode(+new Date()); + if (now !== prev) + return seed = 0, prev = now; + return now + '.' + encode(seed++); +} +// +// Map each character to its index. +// +for (; i < length; i++) + map[alphabet[i]] = i; diff --git a/node_modules/engine.io-client/build/esm/globalThis.browser.d.ts b/node_modules/engine.io-client/build/esm/globalThis.browser.d.ts new file mode 100644 index 0000000..28d0a7c --- /dev/null +++ b/node_modules/engine.io-client/build/esm/globalThis.browser.d.ts @@ -0,0 +1 @@ +export declare const globalThisShim: any; diff --git a/node_modules/engine.io-client/build/esm/globalThis.browser.js b/node_modules/engine.io-client/build/esm/globalThis.browser.js new file mode 100644 index 0000000..ac26899 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/globalThis.browser.js @@ -0,0 +1,11 @@ +export const globalThisShim = (() => { + if (typeof self !== "undefined") { + return self; + } + else if (typeof window !== "undefined") { + return window; + } + else { + return Function("return this")(); + } +})(); diff --git a/node_modules/engine.io-client/build/esm/globalThis.d.ts b/node_modules/engine.io-client/build/esm/globalThis.d.ts new file mode 100644 index 0000000..4b9b90f --- /dev/null +++ b/node_modules/engine.io-client/build/esm/globalThis.d.ts @@ -0,0 +1 @@ +export declare const globalThisShim: typeof globalThis; diff --git a/node_modules/engine.io-client/build/esm/globalThis.js b/node_modules/engine.io-client/build/esm/globalThis.js new file mode 100644 index 0000000..27a616b --- /dev/null +++ b/node_modules/engine.io-client/build/esm/globalThis.js @@ -0,0 +1 @@ +export const globalThisShim = global; diff --git a/node_modules/engine.io-client/build/esm/index.d.ts b/node_modules/engine.io-client/build/esm/index.d.ts new file mode 100644 index 0000000..dca50e8 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/index.d.ts @@ -0,0 +1,8 @@ +import { Socket } from "./socket.js"; +export { Socket }; +export { SocketOptions } from "./socket.js"; +export declare const protocol: number; +export { Transport } from "./transport.js"; +export { transports } from "./transports/index.js"; +export { installTimerFunctions } from "./util.js"; +export { parse } from "./contrib/parseuri.js"; diff --git a/node_modules/engine.io-client/build/esm/index.js b/node_modules/engine.io-client/build/esm/index.js new file mode 100644 index 0000000..7394127 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/index.js @@ -0,0 +1,7 @@ +import { Socket } from "./socket.js"; +export { Socket }; +export const protocol = Socket.protocol; +export { Transport } from "./transport.js"; +export { transports } from "./transports/index.js"; +export { installTimerFunctions } from "./util.js"; +export { parse } from "./contrib/parseuri.js"; diff --git a/node_modules/engine.io-client/build/esm/package.json b/node_modules/engine.io-client/build/esm/package.json new file mode 100644 index 0000000..89498b3 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/package.json @@ -0,0 +1,10 @@ +{ + "name": "engine.io-client", + "type": "module", + "browser": { + "ws": false, + "./transports/xmlhttprequest.js": "./transports/xmlhttprequest.browser.js", + "./transports/websocket-constructor.js": "./transports/websocket-constructor.browser.js", + "./globalThis.js": "./globalThis.browser.js" + } +} diff --git a/node_modules/engine.io-client/build/esm/socket.d.ts b/node_modules/engine.io-client/build/esm/socket.d.ts new file mode 100644 index 0000000..d2999cf --- /dev/null +++ b/node_modules/engine.io-client/build/esm/socket.d.ts @@ -0,0 +1,352 @@ +import { Emitter } from "@socket.io/component-emitter"; +import { CloseDetails } from "./transport.js"; +export interface SocketOptions { + /** + * The host that we're connecting to. Set from the URI passed when connecting + */ + host: string; + /** + * The hostname for our connection. Set from the URI passed when connecting + */ + hostname: string; + /** + * If this is a secure connection. Set from the URI passed when connecting + */ + secure: boolean; + /** + * The port for our connection. Set from the URI passed when connecting + */ + port: string | number; + /** + * Any query parameters in our uri. Set from the URI passed when connecting + */ + query: { + [key: string]: any; + }; + /** + * `http.Agent` to use, defaults to `false` (NodeJS only) + */ + agent: string | boolean; + /** + * Whether the client should try to upgrade the transport from + * long-polling to something better. + * @default true + */ + upgrade: boolean; + /** + * Forces base 64 encoding for polling transport even when XHR2 + * responseType is available and WebSocket even if the used standard + * supports binary. + */ + forceBase64: boolean; + /** + * The param name to use as our timestamp key + * @default 't' + */ + timestampParam: string; + /** + * Whether to add the timestamp with each transport request. Note: this + * is ignored if the browser is IE or Android, in which case requests + * are always stamped + * @default false + */ + timestampRequests: boolean; + /** + * A list of transports to try (in order). Engine.io always attempts to + * connect directly with the first one, provided the feature detection test + * for it passes. + * @default ['polling','websocket'] + */ + transports: string[]; + /** + * The port the policy server listens on + * @default 843 + */ + policyPost: number; + /** + * If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will + * initially try websocket. A connection attempt following a transport error + * will use the normal upgrade process. It is recommended you turn this on + * only when using SSL/TLS connections, or if you know that your network does + * not block websockets. + * @default false + */ + rememberUpgrade: boolean; + /** + * Are we only interested in transports that support binary? + */ + onlyBinaryUpgrades: boolean; + /** + * Timeout for xhr-polling requests in milliseconds (0) (only for polling transport) + */ + requestTimeout: number; + /** + * Transport options for Node.js client (headers etc) + */ + transportOptions: Object; + /** + * (SSL) Certificate, Private key and CA certificates to use for SSL. + * Can be used in Node.js client environment to manually specify + * certificate information. + */ + pfx: string; + /** + * (SSL) Private key to use for SSL. Can be used in Node.js client + * environment to manually specify certificate information. + */ + key: string; + /** + * (SSL) A string or passphrase for the private key or pfx. Can be + * used in Node.js client environment to manually specify certificate + * information. + */ + passphrase: string; + /** + * (SSL) Public x509 certificate to use. Can be used in Node.js client + * environment to manually specify certificate information. + */ + cert: string; + /** + * (SSL) An authority certificate or array of authority certificates to + * check the remote host against.. Can be used in Node.js client + * environment to manually specify certificate information. + */ + ca: string | string[]; + /** + * (SSL) A string describing the ciphers to use or exclude. Consult the + * [cipher format list] + * (http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for + * details on the format.. Can be used in Node.js client environment to + * manually specify certificate information. + */ + ciphers: string; + /** + * (SSL) If true, the server certificate is verified against the list of + * supplied CAs. An 'error' event is emitted if verification fails. + * Verification happens at the connection level, before the HTTP request + * is sent. Can be used in Node.js client environment to manually specify + * certificate information. + */ + rejectUnauthorized: boolean; + /** + * Headers that will be passed for each request to the server (via xhr-polling and via websockets). + * These values then can be used during handshake or for special proxies. + */ + extraHeaders?: { + [header: string]: string; + }; + /** + * Whether to include credentials (cookies, authorization headers, TLS + * client certificates, etc.) with cross-origin XHR polling requests + * @default false + */ + withCredentials: boolean; + /** + * Whether to automatically close the connection whenever the beforeunload event is received. + * @default true + */ + closeOnBeforeunload: boolean; + /** + * Whether to always use the native timeouts. This allows the client to + * reconnect when the native timeout functions are overridden, such as when + * mock clocks are installed. + * @default false + */ + useNativeTimers: boolean; + /** + * weather we should unref the reconnect timer when it is + * create automatically + * @default false + */ + autoUnref: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. + * @default false + */ + perMessageDeflate: { + threshold: number; + }; + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/engine.io' + */ + path: string; + /** + * Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, + * so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to + * be able to handle different types of interactions depending on the specified protocol) + * @default [] + */ + protocols: string | string[]; +} +interface SocketReservedEvents { + open: () => void; + handshake: (data: any) => void; + packet: (packet: any) => void; + packetCreate: (packet: any) => void; + data: (data: any) => void; + message: (data: any) => void; + drain: () => void; + flush: () => void; + heartbeat: () => void; + ping: () => void; + pong: () => void; + error: (err: string | Error) => void; + upgrading: (transport: any) => void; + upgrade: (transport: any) => void; + upgradeError: (err: Error) => void; + close: (reason: string, description?: CloseDetails | Error) => void; +} +export declare class Socket extends Emitter<{}, {}, SocketReservedEvents> { + id: string; + transport: any; + binaryType: string; + private readyState; + private writeBuffer; + private prevBufferLen; + private upgrades; + private pingInterval; + private pingTimeout; + private pingTimeoutTimer; + private setTimeoutFn; + private clearTimeoutFn; + private offlineEventListener; + private upgrading; + private maxPayload?; + private readonly opts; + private readonly secure; + private readonly hostname; + private readonly port; + private readonly transports; + static priorWebsocketSuccess: boolean; + static protocol: number; + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri: any, opts?: Partial); + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + private createTransport; + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + private open; + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + private setTransport; + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + private probe; + /** + * Called when connection is deemed open. + * + * @api private + */ + private onOpen; + /** + * Handles a packet. + * + * @api private + */ + private onPacket; + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + private onHandshake; + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + private resetPingTimeout; + /** + * Called on `drain` event + * + * @api private + */ + private onDrain; + /** + * Flush write buffers. + * + * @api private + */ + private flush; + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + private getWritablePackets; + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg: any, options: any, fn?: any): this; + send(msg: any, options: any, fn?: any): this; + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + private sendPacket; + /** + * Closes the connection. + * + * @api public + */ + close(): this; + /** + * Called upon transport error + * + * @api private + */ + private onError; + /** + * Called upon transport close. + * + * @api private + */ + private onClose; + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + private filterUpgrades; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm/socket.js b/node_modules/engine.io-client/build/esm/socket.js new file mode 100644 index 0000000..617f5cc --- /dev/null +++ b/node_modules/engine.io-client/build/esm/socket.js @@ -0,0 +1,579 @@ +import { transports } from "./transports/index.js"; +import { installTimerFunctions, byteLength } from "./util.js"; +import { decode } from "./contrib/parseqs.js"; +import { parse } from "./contrib/parseuri.js"; +import { Emitter } from "@socket.io/component-emitter"; +import { protocol } from "engine.io-parser"; +export class Socket extends Emitter { + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + constructor(uri, opts = {}) { + super(); + if (uri && "object" === typeof uri) { + opts = uri; + uri = null; + } + if (uri) { + uri = parse(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) + opts.query = uri.query; + } + else if (opts.host) { + opts.hostname = parse(opts.host).host; + } + installTimerFunctions(this, opts); + this.secure = + null != opts.secure + ? opts.secure + : typeof location !== "undefined" && "https:" === location.protocol; + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = this.secure ? "443" : "80"; + } + this.hostname = + opts.hostname || + (typeof location !== "undefined" ? location.hostname : "localhost"); + this.port = + opts.port || + (typeof location !== "undefined" && location.port + ? location.port + : this.secure + ? "443" + : "80"); + this.transports = opts.transports || ["polling", "websocket"]; + this.readyState = ""; + this.writeBuffer = []; + this.prevBufferLen = 0; + this.opts = Object.assign({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + this.opts.path = this.opts.path.replace(/\/$/, "") + "/"; + if (typeof this.opts.query === "string") { + this.opts.query = decode(this.opts.query); + } + // set on handshake + this.id = null; + this.upgrades = null; + this.pingInterval = null; + this.pingTimeout = null; + // set on heartbeat + this.pingTimeoutTimer = null; + if (typeof addEventListener === "function") { + if (this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", () => { + if (this.transport) { + // silently close the transport + this.transport.removeAllListeners(); + this.transport.close(); + } + }, false); + } + if (this.hostname !== "localhost") { + this.offlineEventListener = () => { + this.onClose("transport close", { + description: "network connection lost" + }); + }; + addEventListener("offline", this.offlineEventListener, false); + } + } + this.open(); + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + createTransport(name) { + const query = Object.assign({}, this.opts.query); + // append engine.io protocol identifier + query.EIO = protocol; + // transport name + query.transport = name; + // session id if we already have one + if (this.id) + query.sid = this.id; + const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, { + query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + return new transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + open() { + let transport; + if (this.opts.rememberUpgrade && + Socket.priorWebsocketSuccess && + this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } + else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(() => { + this.emitReserved("error", "No transports available"); + }, 0); + return; + } + else { + transport = this.transports[0]; + } + this.readyState = "opening"; + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } + catch (e) { + this.transports.shift(); + this.open(); + return; + } + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + setTransport(transport) { + if (this.transport) { + this.transport.removeAllListeners(); + } + // set up transport + this.transport = transport; + // set up transport listeners + transport + .on("drain", this.onDrain.bind(this)) + .on("packet", this.onPacket.bind(this)) + .on("error", this.onError.bind(this)) + .on("close", reason => this.onClose("transport close", reason)); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + probe(name) { + let transport = this.createTransport(name); + let failed = false; + Socket.priorWebsocketSuccess = false; + const onTransportOpen = () => { + if (failed) + return; + transport.send([{ type: "ping", data: "probe" }]); + transport.once("packet", msg => { + if (failed) + return; + if ("pong" === msg.type && "probe" === msg.data) { + this.upgrading = true; + this.emitReserved("upgrading", transport); + if (!transport) + return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + this.transport.pause(() => { + if (failed) + return; + if ("closed" === this.readyState) + return; + cleanup(); + this.setTransport(transport); + transport.send([{ type: "upgrade" }]); + this.emitReserved("upgrade", transport); + transport = null; + this.upgrading = false; + this.flush(); + }); + } + else { + const err = new Error("probe error"); + // @ts-ignore + err.transport = transport.name; + this.emitReserved("upgradeError", err); + } + }); + }; + function freezeTransport() { + if (failed) + return; + // Any callback called by transport should be ignored since now + failed = true; + cleanup(); + transport.close(); + transport = null; + } + // Handle any error that happens while probing + const onerror = err => { + const error = new Error("probe error: " + err); + // @ts-ignore + error.transport = transport.name; + freezeTransport(); + this.emitReserved("upgradeError", error); + }; + function onTransportClose() { + onerror("transport closed"); + } + // When the socket is closed while we're probing + function onclose() { + onerror("socket closed"); + } + // When the socket is upgraded while we're probing + function onupgrade(to) { + if (transport && to.name !== transport.name) { + freezeTransport(); + } + } + // Remove all listeners on the transport and on self + const cleanup = () => { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + this.off("close", onclose); + this.off("upgrading", onupgrade); + }; + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + onOpen() { + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); + // we check for `readyState` in case an `open` + // listener already closed the socket + if ("open" === this.readyState && + this.opts.upgrade && + this.transport.pause) { + let i = 0; + const l = this.upgrades.length; + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + onPacket(packet) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + this.emitReserved("packet", packet); + // Socket is live - any packet counts + this.emitReserved("heartbeat"); + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + case "error": + const err = new Error("server error"); + // @ts-ignore + err.code = packet.data; + this.onError(err); + break; + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + else { + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.maxPayload = data.maxPayload; + this.onOpen(); + // In case open handler closes socket + if ("closed" === this.readyState) + return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + resetPingTimeout() { + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(() => { + this.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } + else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + flush() { + if ("closed" !== this.readyState && + this.transport.writable && + !this.upgrading && + this.writeBuffer.length) { + const packets = this.getWritablePackets(); + this.transport.send(packets); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = packets.length; + this.emitReserved("flush"); + } + } + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + getWritablePackets() { + const shouldCheckPayloadSize = this.maxPayload && + this.transport.name === "polling" && + this.writeBuffer.length > 1; + if (!shouldCheckPayloadSize) { + return this.writeBuffer; + } + let payloadSize = 1; // first packet type + for (let i = 0; i < this.writeBuffer.length; i++) { + const data = this.writeBuffer[i].data; + if (data) { + payloadSize += byteLength(data); + } + if (i > 0 && payloadSize > this.maxPayload) { + return this.writeBuffer.slice(0, i); + } + payloadSize += 2; // separator + packet type + } + return this.writeBuffer; + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + if ("function" === typeof options) { + fn = options; + options = null; + } + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + options = options || {}; + options.compress = false !== options.compress; + const packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) + this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + close() { + const close = () => { + this.onClose("forced close"); + this.transport.close(); + }; + const cleanupAndClose = () => { + this.off("upgrade", cleanupAndClose); + this.off("upgradeError", cleanupAndClose); + close(); + }; + const waitForUpgrade = () => { + // wait for upgrade to finish since we can't send packets while pausing a transport + this.once("upgrade", cleanupAndClose); + this.once("upgradeError", cleanupAndClose); + }; + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + if (this.writeBuffer.length) { + this.once("drain", () => { + if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + }); + } + else if (this.upgrading) { + waitForUpgrade(); + } + else { + close(); + } + } + return this; + } + /** + * Called upon transport error + * + * @api private + */ + onError(err) { + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + onClose(reason, description) { + if ("opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState) { + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); + // stop event from firing again for transport + this.transport.removeAllListeners("close"); + // ensure transport won't stay open + this.transport.close(); + // ignore further transport communication + this.transport.removeAllListeners(); + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } + // set ready state + this.readyState = "closed"; + // clear session id + this.id = null; + // emit close event + this.emitReserved("close", reason, description); + // clean buffers after, so users can still + // grab the buffers on `close` event + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + filterUpgrades(upgrades) { + const filteredUpgrades = []; + let i = 0; + const j = upgrades.length; + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) + filteredUpgrades.push(upgrades[i]); + } + return filteredUpgrades; + } +} +Socket.protocol = protocol; diff --git a/node_modules/engine.io-client/build/esm/transport.d.ts b/node_modules/engine.io-client/build/esm/transport.d.ts new file mode 100644 index 0000000..b919100 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transport.d.ts @@ -0,0 +1,96 @@ +import { Packet, RawData } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +import { SocketOptions } from "./socket.js"; +declare class TransportError extends Error { + readonly description: any; + readonly context: any; + readonly type = "TransportError"; + constructor(reason: string, description: any, context: any); +} +export interface CloseDetails { + description: string; + context?: CloseEvent | XMLHttpRequest; +} +interface TransportReservedEvents { + open: () => void; + error: (err: TransportError) => void; + packet: (packet: Packet) => void; + close: (details?: CloseDetails) => void; + poll: () => void; + pollComplete: () => void; + drain: () => void; +} +export declare abstract class Transport extends Emitter<{}, {}, TransportReservedEvents> { + protected opts: SocketOptions; + protected supportsBinary: boolean; + protected query: object; + protected readyState: string; + protected writable: boolean; + protected socket: any; + protected setTimeoutFn: typeof setTimeout; + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts: any); + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + protected onError(reason: string, description: any, context?: any): this; + /** + * Opens the transport. + * + * @api public + */ + private open; + /** + * Closes the transport. + * + * @api public + */ + close(): this; + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets: any): void; + /** + * Called upon open + * + * @api protected + */ + protected onOpen(): void; + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + protected onData(data: RawData): void; + /** + * Called with a decoded packet. + * + * @api protected + */ + protected onPacket(packet: Packet): void; + /** + * Called upon close. + * + * @api protected + */ + protected onClose(details?: CloseDetails): void; + protected abstract doOpen(): any; + protected abstract doClose(): any; + protected abstract write(packets: any): any; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm/transport.js b/node_modules/engine.io-client/build/esm/transport.js new file mode 100644 index 0000000..436e2a1 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transport.js @@ -0,0 +1,116 @@ +import { decodePacket } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +import { installTimerFunctions } from "./util.js"; +class TransportError extends Error { + constructor(reason, description, context) { + super(reason); + this.description = description; + this.context = context; + this.type = "TransportError"; + } +} +export class Transport extends Emitter { + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts) { + super(); + this.writable = false; + installTimerFunctions(this, opts); + this.opts = opts; + this.query = opts.query; + this.readyState = ""; + this.socket = opts.socket; + } + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + onError(reason, description, context) { + super.emitReserved("error", new TransportError(reason, description, context)); + return this; + } + /** + * Opens the transport. + * + * @api public + */ + open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + return this; + } + /** + * Closes the transport. + * + * @api public + */ + close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + else { + // this might happen if the transport was silently closed in the beforeunload event handler + } + } + /** + * Called upon open + * + * @api protected + */ + onOpen() { + this.readyState = "open"; + this.writable = true; + super.emitReserved("open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + onData(data) { + const packet = decodePacket(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + onPacket(packet) { + super.emitReserved("packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + onClose(details) { + this.readyState = "closed"; + super.emitReserved("close", details); + } +} diff --git a/node_modules/engine.io-client/build/esm/transports/index.d.ts b/node_modules/engine.io-client/build/esm/transports/index.d.ts new file mode 100644 index 0000000..8a89404 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/index.d.ts @@ -0,0 +1,6 @@ +import { Polling } from "./polling.js"; +import { WS } from "./websocket.js"; +export declare const transports: { + websocket: typeof WS; + polling: typeof Polling; +}; diff --git a/node_modules/engine.io-client/build/esm/transports/index.js b/node_modules/engine.io-client/build/esm/transports/index.js new file mode 100644 index 0000000..31fc7fa --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/index.js @@ -0,0 +1,6 @@ +import { Polling } from "./polling.js"; +import { WS } from "./websocket.js"; +export const transports = { + websocket: WS, + polling: Polling +}; diff --git a/node_modules/engine.io-client/build/esm/transports/polling.d.ts b/node_modules/engine.io-client/build/esm/transports/polling.d.ts new file mode 100644 index 0000000..2b47956 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/polling.d.ts @@ -0,0 +1,142 @@ +import { Transport } from "../transport.js"; +import { RawData } from "engine.io-parser"; +import { Emitter } from "@socket.io/component-emitter"; +export declare class Polling extends Transport { + private readonly xd; + private readonly xs; + private polling; + private pollXhr; + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts: any); + /** + * Transport name. + */ + get name(): string; + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen(): void; + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause: any): void; + /** + * Starts polling cycle. + * + * @api public + */ + poll(): void; + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data: any): void; + /** + * For polling, send a close packet. + * + * @api private + */ + doClose(): void; + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets: any): void; + /** + * Generates uri for connection. + * + * @api private + */ + uri(): string; + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts?: {}): Request; + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data: any, fn: any): void; + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll(): void; +} +interface RequestReservedEvents { + success: () => void; + data: (data: RawData) => void; + error: (err: number | Error, context: XMLHttpRequest) => void; +} +export declare class Request extends Emitter<{}, {}, RequestReservedEvents> { + private readonly opts; + private readonly method; + private readonly uri; + private readonly async; + private readonly data; + private xhr; + private setTimeoutFn; + private index; + static requestsCount: number; + static requests: {}; + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri: any, opts: any); + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + private create; + /** + * Called upon error. + * + * @api private + */ + private onError; + /** + * Cleans up house. + * + * @api private + */ + private cleanup; + /** + * Called upon load. + * + * @api private + */ + private onLoad; + /** + * Aborts the request. + * + * @api public + */ + abort(): void; +} +export {}; diff --git a/node_modules/engine.io-client/build/esm/transports/polling.js b/node_modules/engine.io-client/build/esm/transports/polling.js new file mode 100644 index 0000000..11e4128 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/polling.js @@ -0,0 +1,403 @@ +import { Transport } from "../transport.js"; +import { yeast } from "../contrib/yeast.js"; +import { encode } from "../contrib/parseqs.js"; +import { encodePayload, decodePayload } from "engine.io-parser"; +import { XHR as XMLHttpRequest } from "./xmlhttprequest.js"; +import { Emitter } from "@socket.io/component-emitter"; +import { installTimerFunctions, pick } from "../util.js"; +import { globalThisShim as globalThis } from "../globalThis.js"; +function empty() { } +const hasXHR2 = (function () { + const xhr = new XMLHttpRequest({ + xdomain: false + }); + return null != xhr.responseType; +})(); +export class Polling extends Transport { + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + constructor(opts) { + super(opts); + this.polling = false; + if (typeof location !== "undefined") { + const isSSL = "https:" === location.protocol; + let port = location.port; + // some user agents have empty `location.port` + if (!port) { + port = isSSL ? "443" : "80"; + } + this.xd = + (typeof location !== "undefined" && + opts.hostname !== location.hostname) || + port !== opts.port; + this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + const forceBase64 = opts && opts.forceBase64; + this.supportsBinary = hasXHR2 && !forceBase64; + } + /** + * Transport name. + */ + get name() { + return "polling"; + } + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + pause(onPause) { + this.readyState = "pausing"; + const pause = () => { + this.readyState = "paused"; + onPause(); + }; + if (this.polling || !this.writable) { + let total = 0; + if (this.polling) { + total++; + this.once("pollComplete", function () { + --total || pause(); + }); + } + if (!this.writable) { + total++; + this.once("drain", function () { + --total || pause(); + }); + } + } + else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + poll() { + this.polling = true; + this.doPoll(); + this.emitReserved("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + onData(data) { + const callback = packet => { + // if its the first message we consider the transport open + if ("opening" === this.readyState && packet.type === "open") { + this.onOpen(); + } + // if its a close packet, we close the ongoing requests + if ("close" === packet.type) { + this.onClose({ description: "transport closed by the server" }); + return false; + } + // otherwise bypass onData and handle the message + this.onPacket(packet); + }; + // decode payload + decodePayload(data, this.socket.binaryType).forEach(callback); + // if an event did not trigger closing + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emitReserved("pollComplete"); + if ("open" === this.readyState) { + this.poll(); + } + else { + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + doClose() { + const close = () => { + this.write([{ type: "close" }]); + }; + if ("open" === this.readyState) { + close(); + } + else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + write(packets) { + this.writable = false; + encodePayload(packets, data => { + this.doWrite(data, () => { + this.writable = true; + this.emitReserved("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "https" : "http"; + let port = ""; + // cache busting is forced + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } + // avoid port if default for schema + if (this.opts.port && + (("https" === schema && Number(this.opts.port) !== 443) || + ("http" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + const encodedQuery = encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + request(opts = {}) { + Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts); + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + doWrite(data, fn) { + const req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", (xhrStatus, context) => { + this.onError("xhr post error", xhrStatus, context); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll() { + const req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", (xhrStatus, context) => { + this.onError("xhr poll error", xhrStatus, context); + }); + this.pollXhr = req; + } +} +export class Request extends Emitter { + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + constructor(uri, opts) { + super(); + installTimerFunctions(this, opts); + this.opts = opts; + this.method = opts.method || "GET"; + this.uri = uri; + this.async = false !== opts.async; + this.data = undefined !== opts.data ? opts.data : null; + this.create(); + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + create() { + const opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + const xhr = (this.xhr = new XMLHttpRequest(opts)); + try { + xhr.open(this.method, this.uri, this.async); + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + for (let i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } + catch (e) { } + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } + catch (e) { } + } + try { + xhr.setRequestHeader("Accept", "*/*"); + } + catch (e) { } + // ie6 check + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + xhr.onreadystatechange = () => { + if (4 !== xhr.readyState) + return; + if (200 === xhr.status || 1223 === xhr.status) { + this.onLoad(); + } + else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + this.setTimeoutFn(() => { + this.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + xhr.send(this.data); + } + catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(() => { + this.onError(e); + }, 0); + return; + } + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon error. + * + * @api private + */ + onError(err) { + this.emitReserved("error", err, this.xhr); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + this.xhr.onreadystatechange = empty; + if (fromError) { + try { + this.xhr.abort(); + } + catch (e) { } + } + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + onLoad() { + const data = this.xhr.responseText; + if (data !== null) { + this.emitReserved("data", data); + this.emitReserved("success"); + this.cleanup(); + } + } + /** + * Aborts the request. + * + * @api public + */ + abort() { + this.cleanup(); + } +} +Request.requestsCount = 0; +Request.requests = {}; +/** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ +if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } + else if (typeof addEventListener === "function") { + const terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } +} +function unloadHandler() { + for (let i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } +} diff --git a/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.d.ts b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.d.ts new file mode 100644 index 0000000..4f1b60e --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.d.ts @@ -0,0 +1,4 @@ +export declare const nextTick: (cb: any, setTimeoutFn: any) => any; +export declare const WebSocket: any; +export declare const usingBrowserWebSocket = true; +export declare const defaultBinaryType = "arraybuffer"; diff --git a/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js new file mode 100644 index 0000000..e49bf1c --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js @@ -0,0 +1,13 @@ +import { globalThisShim as globalThis } from "../globalThis.js"; +export const nextTick = (() => { + const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + if (isPromiseAvailable) { + return cb => Promise.resolve().then(cb); + } + else { + return (cb, setTimeoutFn) => setTimeoutFn(cb, 0); + } +})(); +export const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket; +export const usingBrowserWebSocket = true; +export const defaultBinaryType = "arraybuffer"; diff --git a/node_modules/engine.io-client/build/esm/transports/websocket-constructor.d.ts b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.d.ts new file mode 100644 index 0000000..5509500 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.d.ts @@ -0,0 +1,4 @@ +export declare const WebSocket: any; +export declare const usingBrowserWebSocket = false; +export declare const defaultBinaryType = "nodebuffer"; +export declare const nextTick: (callback: Function, ...args: any[]) => void; diff --git a/node_modules/engine.io-client/build/esm/transports/websocket-constructor.js b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.js new file mode 100644 index 0000000..fd0f46e --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket-constructor.js @@ -0,0 +1,5 @@ +import ws from "ws"; +export const WebSocket = ws; +export const usingBrowserWebSocket = false; +export const defaultBinaryType = "nodebuffer"; +export const nextTick = process.nextTick; diff --git a/node_modules/engine.io-client/build/esm/transports/websocket.d.ts b/node_modules/engine.io-client/build/esm/transports/websocket.d.ts new file mode 100644 index 0000000..837f47a --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket.d.ts @@ -0,0 +1,55 @@ +import { Transport } from "../transport.js"; +export declare class WS extends Transport { + private ws; + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts: any); + /** + * Transport name. + * + * @api public + */ + get name(): string; + /** + * Opens socket. + * + * @api private + */ + doOpen(): this; + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners(): void; + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets: any): void; + /** + * Closes socket. + * + * @api private + */ + doClose(): void; + /** + * Generates uri for connection. + * + * @api private + */ + uri(): string; + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check(): boolean; +} diff --git a/node_modules/engine.io-client/build/esm/transports/websocket.js b/node_modules/engine.io-client/build/esm/transports/websocket.js new file mode 100644 index 0000000..ac5ec91 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/websocket.js @@ -0,0 +1,188 @@ +import { Transport } from "../transport.js"; +import { encode } from "../contrib/parseqs.js"; +import { yeast } from "../contrib/yeast.js"; +import { pick } from "../util.js"; +import { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from "./websocket-constructor.js"; +import { encodePacket } from "engine.io-parser"; +// detect ReactNative environment +const isReactNative = typeof navigator !== "undefined" && + typeof navigator.product === "string" && + navigator.product.toLowerCase() === "reactnative"; +export class WS extends Transport { + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + constructor(opts) { + super(opts); + this.supportsBinary = !opts.forceBase64; + } + /** + * Transport name. + * + * @api public + */ + get name() { + return "websocket"; + } + /** + * Opens socket. + * + * @api private + */ + doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + const uri = this.uri(); + const protocols = this.opts.protocols; + // React Native only supports the 'headers' option, and will print a warning if anything else is passed + const opts = isReactNative + ? {} + : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + try { + this.ws = + usingBrowserWebSocket && !isReactNative + ? protocols + ? new WebSocket(uri, protocols) + : new WebSocket(uri) + : new WebSocket(uri, protocols, opts); + } + catch (err) { + return this.emitReserved("error", err); + } + this.ws.binaryType = this.socket.binaryType || defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + addEventListeners() { + this.ws.onopen = () => { + if (this.opts.autoUnref) { + this.ws._socket.unref(); + } + this.onOpen(); + }; + this.ws.onclose = closeEvent => this.onClose({ + description: "websocket connection closed", + context: closeEvent + }); + this.ws.onmessage = ev => this.onData(ev.data); + this.ws.onerror = e => this.onError("websocket error", e); + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + write(packets) { + this.writable = false; + // encodePacket efficient as it uses WS framing + // no need for encodePayload + for (let i = 0; i < packets.length; i++) { + const packet = packets[i]; + const lastPacket = i === packets.length - 1; + encodePacket(packet, this.supportsBinary, data => { + // always create a new object (GH-437) + const opts = {}; + if (!usingBrowserWebSocket) { + if (packet.options) { + opts.compress = packet.options.compress; + } + if (this.opts.perMessageDeflate) { + const len = + // @ts-ignore + "string" === typeof data ? Buffer.byteLength(data) : data.length; + if (len < this.opts.perMessageDeflate.threshold) { + opts.compress = false; + } + } + } + // Sometimes the websocket has already been closed but the browser didn't + // have a chance of informing us about it yet, in that case send will + // throw an error + try { + if (usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + this.ws.send(data); + } + else { + this.ws.send(data, opts); + } + } + catch (e) { + } + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + nextTick(() => { + this.writable = true; + this.emitReserved("drain"); + }, this.setTimeoutFn); + } + }); + } + } + /** + * Closes socket. + * + * @api private + */ + doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + uri() { + let query = this.query || {}; + const schema = this.opts.secure ? "wss" : "ws"; + let port = ""; + // avoid port if default for schema + if (this.opts.port && + (("wss" === schema && Number(this.opts.port) !== 443) || + ("ws" === schema && Number(this.opts.port) !== 80))) { + port = ":" + this.opts.port; + } + // append timestamp to URI + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + // communicate binary support capabilities + if (!this.supportsBinary) { + query.b64 = 1; + } + const encodedQuery = encode(query); + const ipv6 = this.opts.hostname.indexOf(":") !== -1; + return (schema + + "://" + + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + + port + + this.opts.path + + (encodedQuery.length ? "?" + encodedQuery : "")); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + check() { + return !!WebSocket; + } +} diff --git a/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.d.ts b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.d.ts new file mode 100644 index 0000000..69c00e2 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.d.ts @@ -0,0 +1 @@ +export declare function XHR(opts: any): any; diff --git a/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js new file mode 100644 index 0000000..70c3b1a --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js @@ -0,0 +1,19 @@ +// browser shim for xmlhttprequest module +import { hasCORS } from "../contrib/has-cors.js"; +import { globalThisShim as globalThis } from "../globalThis.js"; +export function XHR(opts) { + const xdomain = opts.xdomain; + // XMLHttpRequest can be disabled on IE + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { + return new XMLHttpRequest(); + } + } + catch (e) { } + if (!xdomain) { + try { + return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } + catch (e) { } + } +} diff --git a/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.d.ts b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.d.ts new file mode 100644 index 0000000..40ca535 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.d.ts @@ -0,0 +1 @@ +export declare const XHR: any; diff --git a/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.js b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.js new file mode 100644 index 0000000..1f66624 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/transports/xmlhttprequest.js @@ -0,0 +1,2 @@ +import * as XMLHttpRequestModule from "xmlhttprequest-ssl"; +export const XHR = XMLHttpRequestModule.default || XMLHttpRequestModule; diff --git a/node_modules/engine.io-client/build/esm/util.d.ts b/node_modules/engine.io-client/build/esm/util.d.ts new file mode 100644 index 0000000..5921b7b --- /dev/null +++ b/node_modules/engine.io-client/build/esm/util.d.ts @@ -0,0 +1,3 @@ +export declare function pick(obj: any, ...attr: any[]): any; +export declare function installTimerFunctions(obj: any, opts: any): void; +export declare function byteLength(obj: any): number; diff --git a/node_modules/engine.io-client/build/esm/util.js b/node_modules/engine.io-client/build/esm/util.js new file mode 100644 index 0000000..335c317 --- /dev/null +++ b/node_modules/engine.io-client/build/esm/util.js @@ -0,0 +1,52 @@ +import { globalThisShim as globalThis } from "./globalThis.js"; +export function pick(obj, ...attr) { + return attr.reduce((acc, k) => { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + return acc; + }, {}); +} +// Keep a reference to the real timeout functions so they can be used when overridden +const NATIVE_SET_TIMEOUT = setTimeout; +const NATIVE_CLEAR_TIMEOUT = clearTimeout; +export function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis); + } + else { + obj.setTimeoutFn = setTimeout.bind(globalThis); + obj.clearTimeoutFn = clearTimeout.bind(globalThis); + } +} +// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) +const BASE64_OVERHEAD = 1.33; +// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 +export function byteLength(obj) { + if (typeof obj === "string") { + return utf8Length(obj); + } + // arraybuffer or blob + return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); +} +function utf8Length(str) { + let c = 0, length = 0; + for (let i = 0, l = str.length; i < l; i++) { + c = str.charCodeAt(i); + if (c < 0x80) { + length += 1; + } + else if (c < 0x800) { + length += 2; + } + else if (c < 0xd800 || c >= 0xe000) { + length += 3; + } + else { + i++; + length += 4; + } + } + return length; +} diff --git a/node_modules/engine.io-client/dist/engine.io.esm.min.js b/node_modules/engine.io-client/dist/engine.io.esm.min.js new file mode 100644 index 0000000..316d782 --- /dev/null +++ b/node_modules/engine.io-client/dist/engine.io.esm.min.js @@ -0,0 +1,7 @@ +/*! + * Engine.IO v6.2.2 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach((s=>{e[t[s]]=s}));const s={type:"error",data:"parser error"},r="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,i=({type:e,data:s},i,a)=>{return r&&s instanceof Blob?i?a(s):n(s,a):o&&(s instanceof ArrayBuffer||(h=s,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(h):h&&h.buffer instanceof ArrayBuffer))?i?a(s):n(new Blob([s]),a):a(t[e]+(s||""));var h},n=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+t)},s.readAsDataURL(t)};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="undefined"==typeof Uint8Array?[]:new Uint8Array(256),p=0;p{if("string"!=typeof t)return{type:"message",data:d(t,r)};const o=t.charAt(0);if("b"===o)return{type:"message",data:u(t.substring(1),r)};return e[o]?t.length>1?{type:e[o],data:t.substring(1)}:{type:e[o]}:s},u=(t,e)=>{if(c){const s=function(t){var e,s,r,o,i,n=.75*t.length,a=t.length,p=0;"="===t[t.length-1]&&(n--,"="===t[t.length-2]&&n--);var c=new ArrayBuffer(n),l=new Uint8Array(c);for(e=0;e>4,l[p++]=(15&r)<<4|o>>2,l[p++]=(3&o)<<6|63&i;return c}(t);return d(s,e)}return{base64:!0,data:t}},d=(t,e)=>"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t,f=String.fromCharCode(30);function y(t){if(t)return function(t){for(var e in y.prototype)t[e]=y.prototype[e];return t}(t)}y.prototype.on=y.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},y.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},y.prototype.off=y.prototype.removeListener=y.prototype.removeAllListeners=y.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}const b=setTimeout,v=clearTimeout;function w(t,e){e.useNativeTimers?(t.setTimeoutFn=b.bind(m),t.clearTimeoutFn=v.bind(m)):(t.setTimeoutFn=setTimeout.bind(m),t.clearTimeoutFn=clearTimeout.bind(m))}class k extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class x extends y{constructor(t){super(),this.writable=!1,w(this,t),this.opts=t,this.query=t.query,this.readyState="",this.socket=t.socket}onError(t,e,s){return super.emitReserved("error",new k(t,e,s)),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}}const T="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),S={};let R,B=0,C=0;function E(t){let e="";do{e=T[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function L(){const t=E(+new Date);return t!==R?(B=0,R=t):t+"."+E(B++)}for(;C<64;C++)S[T[C]]=C;function q(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}let O=!1;try{O="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const P=O;function A(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||P))return new XMLHttpRequest}catch(t){}if(!e)try{return new(m[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function U(){}const H=null!=new A({xdomain:!1}).responseType;class j extends y{constructor(t,e){super(),w(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.create()}create(){const t=g(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;const e=this.xhr=new A(t);try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&e.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),e.onreadystatechange=()=>{4===e.readyState&&(200===e.status||1223===e.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=j.requestsCount++,j.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=U,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete j.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(j.requestsCount=0,j.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",_);else if("function"==typeof addEventListener){addEventListener("onpagehide"in m?"pagehide":"unload",_,!1)}function _(){for(let t in j.requests)j.requests.hasOwnProperty(t)&&j.requests[t].abort()}const F="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),D=m.WebSocket||m.MozWebSocket,I="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const M={websocket:class extends x{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,s=I?{}:g(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=I?new D(t,e,s):e?new D(t,e):new D(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e{try{this.ws.send(t)}catch(t){}r&&F((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let s="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(s=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||(t.b64=1);const r=q(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+s+this.opts.path+(r.length?"?"+r:"")}check(){return!!D}},polling:class extends x{constructor(t){if(super(t),this.polling=!1,"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port,this.xs=t.secure!==e}const e=t&&t.forceBase64;this.supportsBinary=H&&!e}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(f),r=[];for(let t=0;t{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,r=new Array(s);let o=0;t.forEach(((t,n)=>{i(t,!1,(t=>{r[n]=t,++o===s&&e(r.join(f))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let t=this.query||{};const e=this.opts.secure?"https":"http";let s="";!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=L()),this.supportsBinary||t.sid||(t.b64=1),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(s=":"+this.opts.port);const r=q(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+s+this.opts.path+(r.length?"?"+r:"")}request(t={}){return Object.assign(t,{xd:this.xd,xs:this.xs},this.opts),new j(this.uri(),t)}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",((t,e)=>{this.onError("xhr post error",t,e)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",((t,e)=>{this.onError("xhr poll error",t,e)})),this.pollXhr=t}}},W=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,N=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X(t){const e=t,s=t.indexOf("["),r=t.indexOf("]");-1!=s&&-1!=r&&(t=t.substring(0,s)+t.substring(s,r).replace(/:/g,";")+t.substring(r,t.length));let o=W.exec(t||""),i={},n=14;for(;n--;)i[N[n]]=o[n]||"";return-1!=s&&-1!=r&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(t,e){const s=/\/{2,9}/g,r=e.replace(s,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||r.splice(0,1);"/"==e.substr(e.length-1,1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(s[e]=r)})),s}(0,i.query),i}class $ extends y{constructor(t,e={}){super(),t&&"object"==typeof t&&(e=t,t=null),t?(t=X(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=X(e.host).host),w(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,r=s.length;t{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new M[t](s)}open(){let t;if(this.opts.rememberUpgrade&&$.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(t=>this.onClose("transport close",t)))}probe(t){let e=this.createTransport(t),s=!1;$.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;$.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(p(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function o(){s||(s=!0,p(),e.close(),e=null)}const i=t=>{const s=new Error("probe error: "+t);s.transport=e.name,o(),this.emitReserved("upgradeError",s)};function n(){i("transport closed")}function a(){i("socket closed")}function h(t){e&&t.name!==e.name&&o()}const p=()=>{e.removeListener("open",r),e.removeListener("error",i),e.removeListener("close",n),this.off("close",a),this.off("upgrading",h)};e.once("open",r),e.once("error",i),e.once("close",n),this.once("close",a),this.once("upgrading",h),e.open()}onOpen(){if(this.readyState="open",$.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let t=0;const e=this.upgrades.length;for(;t{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}write(t,e,s){return this.sendPacket("message",t,e,s),this}send(t,e,s){return this.sendPacket("message",t,e,s),this}sendPacket(t,e,s,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const o={type:t,data:e,options:s};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}onError(t){$.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let s=0;const r=t.length;for(;s {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export const globalThisShim = (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import { globalThisShim as globalThis } from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nexport function XHR(opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport { XHR as XMLHttpRequest } from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import { globalThisShim as globalThis } from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return !!WebSocket;\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","import { Socket } from \"./socket.js\";\nexport { Socket };\nexport const protocol = Socket.protocol;\nexport { Transport } from \"./transport.js\";\nexport { transports } from \"./transports/index.js\";\nexport { installTimerFunctions } from \"./util.js\";\nexport { parse } from \"./contrib/parseuri.js\";\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","encodePacket","supportsBinary","callback","encodeBlobAsBase64","obj","isView","buffer","fileReader","FileReader","onload","content","result","split","readAsDataURL","chars","lookup","Uint8Array","i","length","charCodeAt","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","decoded","base64","encoded1","encoded2","encoded3","encoded4","bufferLength","len","p","arraybuffer","bytes","decode","SEPARATOR","String","fromCharCode","Emitter","mixin","on","addEventListener","event","fn","this","_callbacks","push","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","cb","callbacks","splice","emit","args","Array","slice","emitReserved","listeners","hasListeners","globalThisShim","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","TransportError","Error","constructor","reason","description","context","super","Transport","writable","query","readyState","socket","onError","open","doOpen","close","doClose","onClose","send","packets","write","onOpen","onData","packet","onPacket","details","alphabet","map","prev","seed","encode","num","encoded","Math","floor","yeast","now","Date","str","encodeURIComponent","value","XMLHttpRequest","err","hasCORS","XHR","xdomain","e","concat","join","empty","hasXHR2","responseType","Request","uri","method","async","undefined","xd","xscheme","xs","xhr","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","onLoad","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","nextTick","Promise","resolve","then","WebSocket","MozWebSocket","isReactNative","navigator","product","toLowerCase","transports","websocket","forceBase64","name","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","schema","secure","port","Number","timestampRequests","timestampParam","b64","encodedQuery","hostname","indexOf","path","polling","location","isSSL","protocol","poll","pause","onPause","total","doPoll","encodedPayload","encodedPackets","decodedPacket","decodePayload","count","encodePayload","doWrite","sid","request","assign","req","xhrStatus","pollXhr","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","regx","names","substr","queryKey","$0","$1","$2","Socket","writeBuffer","prevBufferLen","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","qs","qry","pairs","l","pair","decodeURIComponent","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","createTransport","EIO","priorWebsocketSuccess","shift","setTransport","onDrain","probe","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","payloadSize","c","utf8Length","ceil","byteLength","size","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j"],"mappings":";;;;;AAAA,MAAMA,EAAeC,OAAOC,OAAO,MACnCF,EAAmB,KAAI,IACvBA,EAAoB,MAAI,IACxBA,EAAmB,KAAI,IACvBA,EAAmB,KAAI,IACvBA,EAAsB,QAAI,IAC1BA,EAAsB,QAAI,IAC1BA,EAAmB,KAAI,IACvB,MAAMG,EAAuBF,OAAOC,OAAO,MAC3CD,OAAOG,KAAKJ,GAAcK,SAAQC,IAC9BH,EAAqBH,EAAaM,IAAQA,KAE9C,MAAMC,EAAe,CAAEC,KAAM,QAASC,KAAM,gBCXtCC,EAAiC,mBAATC,MACT,oBAATA,MACqC,6BAAzCV,OAAOW,UAAUC,SAASC,KAAKH,MACjCI,EAA+C,mBAAhBC,YAO/BC,EAAe,EAAGT,KAAAA,EAAMC,KAAAA,GAAQS,EAAgBC,KAClD,OAAIT,GAAkBD,aAAgBE,KAC9BO,EACOC,EAASV,GAGTW,EAAmBX,EAAMU,GAG/BJ,IACJN,aAAgBO,cAfVK,EAegCZ,EAdN,mBAAvBO,YAAYM,OACpBN,YAAYM,OAAOD,GACnBA,GAAOA,EAAIE,kBAAkBP,cAa3BE,EACOC,EAASV,GAGTW,EAAmB,IAAIT,KAAK,CAACF,IAAQU,GAI7CA,EAASnB,EAAaQ,IAASC,GAAQ,KAxBnCY,IAAAA,GA0BTD,EAAqB,CAACX,EAAMU,KAC9B,MAAMK,EAAa,IAAIC,WAKvB,OAJAD,EAAWE,OAAS,WAChB,MAAMC,EAAUH,EAAWI,OAAOC,MAAM,KAAK,GAC7CV,EAAS,IAAMQ,IAEZH,EAAWM,cAAcrB,IC9BpC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UAAUzK,QAEfxD,KAAKiO,UAAUzN,qBACoB,mBAAxBC,qBACPA,oBAAoB,UAAWT,KAAKkO,sBAAsB,GAG9DlO,KAAKmD,WAAa,SAElBnD,KAAK4N,GAAK,KAEV5N,KAAKiB,aAAa,QAAS2B,EAAQC,GAGnC7C,KAAK4M,YAAc,GACnB5M,KAAK6M,cAAgB,GAU7B4C,eAAe5B,GACX,MAAMyC,EAAmB,GACzB,IAAIrS,EAAI,EACR,MAAMsS,EAAI1C,EAAS3P,OACnB,KAAOD,EAAIsS,EAAGtS,KACL+B,KAAKmI,WAAW4B,QAAQ8D,EAAS5P,KAClCqS,EAAiBpQ,KAAK2N,EAAS5P,IAEvC,OAAOqS,GAGf3D,EAAOvC,SdpiBiB,Ee5BZ,MAACA,EAAWuC,EAAOvC"} \ No newline at end of file diff --git a/node_modules/engine.io-client/dist/engine.io.js b/node_modules/engine.io-client/dist/engine.io.js new file mode 100644 index 0000000..521f5a6 --- /dev/null +++ b/node_modules/engine.io-client/dist/engine.io.js @@ -0,0 +1,2435 @@ +/*! + * Engine.IO v6.2.2 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.eio = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); + } + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); + } + + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); + } + + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; + } + + function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } + + return _assertThisInitialized(self); + } + + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return _possibleConstructorReturn(this, result); + }; + } + + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + + return object; + } + + function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); + } + + var PACKET_TYPES = Object.create(null); // no Map = no polyfill + + PACKET_TYPES["open"] = "0"; + PACKET_TYPES["close"] = "1"; + PACKET_TYPES["ping"] = "2"; + PACKET_TYPES["pong"] = "3"; + PACKET_TYPES["message"] = "4"; + PACKET_TYPES["upgrade"] = "5"; + PACKET_TYPES["noop"] = "6"; + var PACKET_TYPES_REVERSE = Object.create(null); + Object.keys(PACKET_TYPES).forEach(function (key) { + PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; + }); + var ERROR_PACKET = { + type: "error", + data: "parser error" + }; + + var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]"; + var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10 + + var isView = function isView(obj) { + return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer; + }; + + var encodePacket = function encodePacket(_ref, supportsBinary, callback) { + var type = _ref.type, + data = _ref.data; + + if (withNativeBlob && data instanceof Blob) { + if (supportsBinary) { + return callback(data); + } else { + return encodeBlobAsBase64(data, callback); + } + } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) { + if (supportsBinary) { + return callback(data); + } else { + return encodeBlobAsBase64(new Blob([data]), callback); + } + } // plain string + + + return callback(PACKET_TYPES[type] + (data || "")); + }; + + var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) { + var fileReader = new FileReader(); + + fileReader.onload = function () { + var content = fileReader.result.split(",")[1]; + callback("b" + content); + }; + + return fileReader.readAsDataURL(data); + }; + + /* + * base64-arraybuffer 1.0.1 + * Copyright (c) 2022 Niklas von Hertzen + * Released under MIT License + */ + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index. + + var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); + + for (var i$1 = 0; i$1 < chars.length; i$1++) { + lookup[chars.charCodeAt(i$1)] = i$1; + } + + var decode$1 = function decode(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, + i, + p = 0, + encoded1, + encoded2, + encoded3, + encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; + }; + + var withNativeArrayBuffer = typeof ArrayBuffer === "function"; + + var decodePacket = function decodePacket(encodedPacket, binaryType) { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + + var type = encodedPacket.charAt(0); + + if (type === "b") { + return { + type: "message", + data: decodeBase64Packet(encodedPacket.substring(1), binaryType) + }; + } + + var packetType = PACKET_TYPES_REVERSE[type]; + + if (!packetType) { + return ERROR_PACKET; + } + + return encodedPacket.length > 1 ? { + type: PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } : { + type: PACKET_TYPES_REVERSE[type] + }; + }; + + var decodeBase64Packet = function decodeBase64Packet(data, binaryType) { + if (withNativeArrayBuffer) { + var decoded = decode$1(data); + return mapBinary(decoded, binaryType); + } else { + return { + base64: true, + data: data + }; // fallback for old browsers + } + }; + + var mapBinary = function mapBinary(data, binaryType) { + switch (binaryType) { + case "blob": + return data instanceof ArrayBuffer ? new Blob([data]) : data; + + case "arraybuffer": + default: + return data; + // assuming the data is already an ArrayBuffer + } + }; + + var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text + + var encodePayload = function encodePayload(packets, callback) { + // some packets may be added to the array while encoding, so the initial length must be saved + var length = packets.length; + var encodedPackets = new Array(length); + var count = 0; + packets.forEach(function (packet, i) { + // force base64 encoding for binary packets + encodePacket(packet, false, function (encodedPacket) { + encodedPackets[i] = encodedPacket; + + if (++count === length) { + callback(encodedPackets.join(SEPARATOR)); + } + }); + }); + }; + + var decodePayload = function decodePayload(encodedPayload, binaryType) { + var encodedPackets = encodedPayload.split(SEPARATOR); + var packets = []; + + for (var i = 0; i < encodedPackets.length; i++) { + var decodedPacket = decodePacket(encodedPackets[i], binaryType); + packets.push(decodedPacket); + + if (decodedPacket.type === "error") { + break; + } + } + + return packets; + }; + + var protocol = 4; + + /** + * Initialize a new `Emitter`. + * + * @api public + */ + function Emitter(obj) { + if (obj) return mixin(obj); + } + /** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + + return obj; + } + /** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) { + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn); + return this; + }; + /** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.once = function (event, fn) { + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; + }; + /** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) { + this._callbacks = this._callbacks || {}; // all + + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } // specific event + + + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; // remove all handlers + + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } // remove specific handler + + + var cb; + + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + + + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; + }; + /** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + + + Emitter.prototype.emit = function (event) { + this._callbacks = this._callbacks || {}; + var args = new Array(arguments.length - 1), + callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; + }; // alias used for reserved events (protected method) + + + Emitter.prototype.emitReserved = Emitter.prototype.emit; + /** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + + Emitter.prototype.listeners = function (event) { + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; + }; + /** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + + + Emitter.prototype.hasListeners = function (event) { + return !!this.listeners(event).length; + }; + + var globalThisShim = function () { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else { + return Function("return this")(); + } + }(); + + function pick(obj) { + for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + attr[_key - 1] = arguments[_key]; + } + + return attr.reduce(function (acc, k) { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + + return acc; + }, {}); + } // Keep a reference to the real timeout functions so they can be used when overridden + + var NATIVE_SET_TIMEOUT = setTimeout; + var NATIVE_CLEAR_TIMEOUT = clearTimeout; + function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim); + } else { + obj.setTimeoutFn = setTimeout.bind(globalThisShim); + obj.clearTimeoutFn = clearTimeout.bind(globalThisShim); + } + } // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) + + var BASE64_OVERHEAD = 1.33; // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 + + function byteLength(obj) { + if (typeof obj === "string") { + return utf8Length(obj); + } // arraybuffer or blob + + + return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); + } + + function utf8Length(str) { + var c = 0, + length = 0; + + for (var i = 0, l = str.length; i < l; i++) { + c = str.charCodeAt(i); + + if (c < 0x80) { + length += 1; + } else if (c < 0x800) { + length += 2; + } else if (c < 0xd800 || c >= 0xe000) { + length += 3; + } else { + i++; + length += 4; + } + } + + return length; + } + + var TransportError = /*#__PURE__*/function (_Error) { + _inherits(TransportError, _Error); + + var _super = _createSuper(TransportError); + + function TransportError(reason, description, context) { + var _this; + + _classCallCheck(this, TransportError); + + _this = _super.call(this, reason); + _this.description = description; + _this.context = context; + _this.type = "TransportError"; + return _this; + } + + return TransportError; + }( /*#__PURE__*/_wrapNativeSuper(Error)); + + var Transport = /*#__PURE__*/function (_Emitter) { + _inherits(Transport, _Emitter); + + var _super2 = _createSuper(Transport); + + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + function Transport(opts) { + var _this2; + + _classCallCheck(this, Transport); + + _this2 = _super2.call(this); + _this2.writable = false; + installTimerFunctions(_assertThisInitialized(_this2), opts); + _this2.opts = opts; + _this2.query = opts.query; + _this2.readyState = ""; + _this2.socket = opts.socket; + return _this2; + } + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + + + _createClass(Transport, [{ + key: "onError", + value: function onError(reason, description, context) { + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context)); + + return this; + } + /** + * Opens the transport. + * + * @api public + */ + + }, { + key: "open", + value: function open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + + return this; + } + /** + * Closes the transport. + * + * @api public + */ + + }, { + key: "close", + value: function close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + + }, { + key: "send", + value: function send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + } + /** + * Called upon open + * + * @api protected + */ + + }, { + key: "onOpen", + value: function onOpen() { + this.readyState = "open"; + this.writable = true; + + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + + }, { + key: "onData", + value: function onData(data) { + var packet = decodePacket(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + + }, { + key: "onPacket", + value: function onPacket(packet) { + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + + }, { + key: "onClose", + value: function onClose(details) { + this.readyState = "closed"; + + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details); + } + }]); + + return Transport; + }(Emitter); + + // imported from https://github.com/unshiftio/yeast + + var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), + length = 64, + map = {}; + var seed = 0, + i = 0, + prev; + /** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ + + function encode$1(num) { + var encoded = ''; + + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + + return encoded; + } + /** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ + + function yeast() { + var now = encode$1(+new Date()); + if (now !== prev) return seed = 0, prev = now; + return now + '.' + encode$1(seed++); + } // + // Map each character to its index. + // + + for (; i < length; i++) { + map[alphabet[i]] = i; + } + + // imported from https://github.com/galkn/querystring + + /** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ + function encode(obj) { + var str = ''; + + for (var i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + + return str; + } + /** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ + + function decode(qs) { + var qry = {}; + var pairs = qs.split('&'); + + for (var i = 0, l = pairs.length; i < l; i++) { + var pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + + return qry; + } + + // imported from https://github.com/component/has-cors + var value = false; + + try { + value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); + } catch (err) {// if XMLHttp support is disabled in IE then it will throw + // when trying to create + } + + var hasCORS = value; + + // browser shim for xmlhttprequest module + function XHR(opts) { + var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE + + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { + return new XMLHttpRequest(); + } + } catch (e) {} + + if (!xdomain) { + try { + return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } catch (e) {} + } + } + + function empty() {} + + var hasXHR2 = function () { + var xhr = new XHR({ + xdomain: false + }); + return null != xhr.responseType; + }(); + + var Polling = /*#__PURE__*/function (_Transport) { + _inherits(Polling, _Transport); + + var _super = _createSuper(Polling); + + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + function Polling(opts) { + var _this; + + _classCallCheck(this, Polling); + + _this = _super.call(this, opts); + _this.polling = false; + + if (typeof location !== "undefined") { + var isSSL = "https:" === location.protocol; + var port = location.port; // some user agents have empty `location.port` + + if (!port) { + port = isSSL ? "443" : "80"; + } + + _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port; + _this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + + + var forceBase64 = opts && opts.forceBase64; + _this.supportsBinary = hasXHR2 && !forceBase64; + return _this; + } + /** + * Transport name. + */ + + + _createClass(Polling, [{ + key: "doOpen", + + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + value: function doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + + }, { + key: "pause", + value: function pause(onPause) { + var _this2 = this; + + this.readyState = "pausing"; + + var pause = function pause() { + _this2.readyState = "paused"; + onPause(); + }; + + if (this.polling || !this.writable) { + var total = 0; + + if (this.polling) { + total++; + this.once("pollComplete", function () { + --total || pause(); + }); + } + + if (!this.writable) { + total++; + this.once("drain", function () { + --total || pause(); + }); + } + } else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + + }, { + key: "poll", + value: function poll() { + this.polling = true; + this.doPoll(); + this.emitReserved("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + + }, { + key: "onData", + value: function onData(data) { + var _this3 = this; + + var callback = function callback(packet) { + // if its the first message we consider the transport open + if ("opening" === _this3.readyState && packet.type === "open") { + _this3.onOpen(); + } // if its a close packet, we close the ongoing requests + + + if ("close" === packet.type) { + _this3.onClose({ + description: "transport closed by the server" + }); + + return false; + } // otherwise bypass onData and handle the message + + + _this3.onPacket(packet); + }; // decode payload + + + decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing + + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emitReserved("pollComplete"); + + if ("open" === this.readyState) { + this.poll(); + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + + }, { + key: "doClose", + value: function doClose() { + var _this4 = this; + + var close = function close() { + _this4.write([{ + type: "close" + }]); + }; + + if ("open" === this.readyState) { + close(); + } else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + + }, { + key: "write", + value: function write(packets) { + var _this5 = this; + + this.writable = false; + encodePayload(packets, function (data) { + _this5.doWrite(data, function () { + _this5.writable = true; + + _this5.emitReserved("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + + }, { + key: "uri", + value: function uri() { + var query = this.query || {}; + var schema = this.opts.secure ? "https" : "http"; + var port = ""; // cache busting is forced + + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } // avoid port if default for schema + + + if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) { + port = ":" + this.opts.port; + } + + var encodedQuery = encode(query); + var ipv6 = this.opts.hostname.indexOf(":") !== -1; + return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : ""); + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + + }, { + key: "request", + value: function request() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _extends(opts, { + xd: this.xd, + xs: this.xs + }, this.opts); + + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + + }, { + key: "doWrite", + value: function doWrite(data, fn) { + var _this6 = this; + + var req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", function (xhrStatus, context) { + _this6.onError("xhr post error", xhrStatus, context); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + + }, { + key: "doPoll", + value: function doPoll() { + var _this7 = this; + + var req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", function (xhrStatus, context) { + _this7.onError("xhr poll error", xhrStatus, context); + }); + this.pollXhr = req; + } + }, { + key: "name", + get: function get() { + return "polling"; + } + }]); + + return Polling; + }(Transport); + var Request = /*#__PURE__*/function (_Emitter) { + _inherits(Request, _Emitter); + + var _super2 = _createSuper(Request); + + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + function Request(uri, opts) { + var _this8; + + _classCallCheck(this, Request); + + _this8 = _super2.call(this); + installTimerFunctions(_assertThisInitialized(_this8), opts); + _this8.opts = opts; + _this8.method = opts.method || "GET"; + _this8.uri = uri; + _this8.async = false !== opts.async; + _this8.data = undefined !== opts.data ? opts.data : null; + + _this8.create(); + + return _this8; + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + + + _createClass(Request, [{ + key: "create", + value: function create() { + var _this9 = this; + + var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + var xhr = this.xhr = new XHR(opts); + + try { + xhr.open(this.method, this.uri, this.async); + + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + + for (var i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } catch (e) {} + + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } catch (e) {} + } + + try { + xhr.setRequestHeader("Accept", "*/*"); + } catch (e) {} // ie6 check + + + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + + xhr.onreadystatechange = function () { + if (4 !== xhr.readyState) return; + + if (200 === xhr.status || 1223 === xhr.status) { + _this9.onLoad(); + } else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + _this9.setTimeoutFn(function () { + _this9.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + + xhr.send(this.data); + } catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(function () { + _this9.onError(e); + }, 0); + return; + } + + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon error. + * + * @api private + */ + + }, { + key: "onError", + value: function onError(err) { + this.emitReserved("error", err, this.xhr); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + + }, { + key: "cleanup", + value: function cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + + this.xhr.onreadystatechange = empty; + + if (fromError) { + try { + this.xhr.abort(); + } catch (e) {} + } + + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + + }, { + key: "onLoad", + value: function onLoad() { + var data = this.xhr.responseText; + + if (data !== null) { + this.emitReserved("data", data); + this.emitReserved("success"); + this.cleanup(); + } + } + /** + * Aborts the request. + * + * @api public + */ + + }, { + key: "abort", + value: function abort() { + this.cleanup(); + } + }]); + + return Request; + }(Emitter); + Request.requestsCount = 0; + Request.requests = {}; + /** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ + + if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } else if (typeof addEventListener === "function") { + var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } + } + + function unloadHandler() { + for (var i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } + } + + var nextTick = function () { + var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + + if (isPromiseAvailable) { + return function (cb) { + return Promise.resolve().then(cb); + }; + } else { + return function (cb, setTimeoutFn) { + return setTimeoutFn(cb, 0); + }; + } + }(); + var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket; + var usingBrowserWebSocket = true; + var defaultBinaryType = "arraybuffer"; + + var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative"; + var WS = /*#__PURE__*/function (_Transport) { + _inherits(WS, _Transport); + + var _super = _createSuper(WS); + + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + function WS(opts) { + var _this; + + _classCallCheck(this, WS); + + _this = _super.call(this, opts); + _this.supportsBinary = !opts.forceBase64; + return _this; + } + /** + * Transport name. + * + * @api public + */ + + + _createClass(WS, [{ + key: "doOpen", + + /** + * Opens socket. + * + * @api private + */ + value: function doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + + var uri = this.uri(); + var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed + + var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + + try { + this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts); + } catch (err) { + return this.emitReserved("error", err); + } + + this.ws.binaryType = this.socket.binaryType || defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + + }, { + key: "addEventListeners", + value: function addEventListeners() { + var _this2 = this; + + this.ws.onopen = function () { + if (_this2.opts.autoUnref) { + _this2.ws._socket.unref(); + } + + _this2.onOpen(); + }; + + this.ws.onclose = function (closeEvent) { + return _this2.onClose({ + description: "websocket connection closed", + context: closeEvent + }); + }; + + this.ws.onmessage = function (ev) { + return _this2.onData(ev.data); + }; + + this.ws.onerror = function (e) { + return _this2.onError("websocket error", e); + }; + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + + }, { + key: "write", + value: function write(packets) { + var _this3 = this; + + this.writable = false; // encodePacket efficient as it uses WS framing + // no need for encodePayload + + var _loop = function _loop(i) { + var packet = packets[i]; + var lastPacket = i === packets.length - 1; + encodePacket(packet, _this3.supportsBinary, function (data) { + // always create a new object (GH-437) + var opts = {}; + // have a chance of informing us about it yet, in that case send will + // throw an error + + + try { + if (usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + _this3.ws.send(data); + } + } catch (e) {} + + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + nextTick(function () { + _this3.writable = true; + + _this3.emitReserved("drain"); + }, _this3.setTimeoutFn); + } + }); + }; + + for (var i = 0; i < packets.length; i++) { + _loop(i); + } + } + /** + * Closes socket. + * + * @api private + */ + + }, { + key: "doClose", + value: function doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + + }, { + key: "uri", + value: function uri() { + var query = this.query || {}; + var schema = this.opts.secure ? "wss" : "ws"; + var port = ""; // avoid port if default for schema + + if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) { + port = ":" + this.opts.port; + } // append timestamp to URI + + + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } // communicate binary support capabilities + + + if (!this.supportsBinary) { + query.b64 = 1; + } + + var encodedQuery = encode(query); + var ipv6 = this.opts.hostname.indexOf(":") !== -1; + return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : ""); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + + }, { + key: "check", + value: function check() { + return !!WebSocket; + } + }, { + key: "name", + get: function get() { + return "websocket"; + } + }]); + + return WS; + }(Transport); + + var transports = { + websocket: WS, + polling: Polling + }; + + // imported from https://github.com/galkn/parseuri + + /** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ + var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor']; + function parse(str) { + var src = str, + b = str.indexOf('['), + e = str.indexOf(']'); + + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + + var m = re.exec(str || ''), + uri = {}, + i = 14; + + while (i--) { + uri[parts[i]] = m[i] || ''; + } + + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + + uri.pathNames = pathNames(uri, uri['path']); + uri.queryKey = queryKey(uri, uri['query']); + return uri; + } + + function pathNames(obj, path) { + var regx = /\/{2,9}/g, + names = path.replace(regx, "/").split("/"); + + if (path.substr(0, 1) == '/' || path.length === 0) { + names.splice(0, 1); + } + + if (path.substr(path.length - 1, 1) == '/') { + names.splice(names.length - 1, 1); + } + + return names; + } + + function queryKey(uri, query) { + var data = {}; + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { + if ($1) { + data[$1] = $2; + } + }); + return data; + } + + var Socket = /*#__PURE__*/function (_Emitter) { + _inherits(Socket, _Emitter); + + var _super = _createSuper(Socket); + + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + function Socket(uri) { + var _this; + + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, Socket); + + _this = _super.call(this); + + if (uri && "object" === _typeof(uri)) { + opts = uri; + uri = null; + } + + if (uri) { + uri = parse(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) opts.query = uri.query; + } else if (opts.host) { + opts.hostname = parse(opts.host).host; + } + + installTimerFunctions(_assertThisInitialized(_this), opts); + _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol; + + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = _this.secure ? "443" : "80"; + } + + _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost"); + _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80"); + _this.transports = opts.transports || ["polling", "websocket"]; + _this.readyState = ""; + _this.writeBuffer = []; + _this.prevBufferLen = 0; + _this.opts = _extends({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/"; + + if (typeof _this.opts.query === "string") { + _this.opts.query = decode(_this.opts.query); + } // set on handshake + + + _this.id = null; + _this.upgrades = null; + _this.pingInterval = null; + _this.pingTimeout = null; // set on heartbeat + + _this.pingTimeoutTimer = null; + + if (typeof addEventListener === "function") { + if (_this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", function () { + if (_this.transport) { + // silently close the transport + _this.transport.removeAllListeners(); + + _this.transport.close(); + } + }, false); + } + + if (_this.hostname !== "localhost") { + _this.offlineEventListener = function () { + _this.onClose("transport close", { + description: "network connection lost" + }); + }; + + addEventListener("offline", _this.offlineEventListener, false); + } + } + + _this.open(); + + return _this; + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + + + _createClass(Socket, [{ + key: "createTransport", + value: function createTransport(name) { + var query = _extends({}, this.opts.query); // append engine.io protocol identifier + + + query.EIO = protocol; // transport name + + query.transport = name; // session id if we already have one + + if (this.id) query.sid = this.id; + + var opts = _extends({}, this.opts.transportOptions[name], this.opts, { + query: query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + + return new transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + + }, { + key: "open", + value: function open() { + var _this2 = this; + + var transport; + + if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(function () { + _this2.emitReserved("error", "No transports available"); + }, 0); + return; + } else { + transport = this.transports[0]; + } + + this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false) + + try { + transport = this.createTransport(transport); + } catch (e) { + this.transports.shift(); + this.open(); + return; + } + + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + + }, { + key: "setTransport", + value: function setTransport(transport) { + var _this3 = this; + + if (this.transport) { + this.transport.removeAllListeners(); + } // set up transport + + + this.transport = transport; // set up transport listeners + + transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) { + return _this3.onClose("transport close", reason); + }); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + + }, { + key: "probe", + value: function probe(name) { + var _this4 = this; + + var transport = this.createTransport(name); + var failed = false; + Socket.priorWebsocketSuccess = false; + + var onTransportOpen = function onTransportOpen() { + if (failed) return; + transport.send([{ + type: "ping", + data: "probe" + }]); + transport.once("packet", function (msg) { + if (failed) return; + + if ("pong" === msg.type && "probe" === msg.data) { + _this4.upgrading = true; + + _this4.emitReserved("upgrading", transport); + + if (!transport) return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + + _this4.transport.pause(function () { + if (failed) return; + if ("closed" === _this4.readyState) return; + cleanup(); + + _this4.setTransport(transport); + + transport.send([{ + type: "upgrade" + }]); + + _this4.emitReserved("upgrade", transport); + + transport = null; + _this4.upgrading = false; + + _this4.flush(); + }); + } else { + var err = new Error("probe error"); // @ts-ignore + + err.transport = transport.name; + + _this4.emitReserved("upgradeError", err); + } + }); + }; + + function freezeTransport() { + if (failed) return; // Any callback called by transport should be ignored since now + + failed = true; + cleanup(); + transport.close(); + transport = null; + } // Handle any error that happens while probing + + + var onerror = function onerror(err) { + var error = new Error("probe error: " + err); // @ts-ignore + + error.transport = transport.name; + freezeTransport(); + + _this4.emitReserved("upgradeError", error); + }; + + function onTransportClose() { + onerror("transport closed"); + } // When the socket is closed while we're probing + + + function onclose() { + onerror("socket closed"); + } // When the socket is upgraded while we're probing + + + function onupgrade(to) { + if (transport && to.name !== transport.name) { + freezeTransport(); + } + } // Remove all listeners on the transport and on self + + + var cleanup = function cleanup() { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + + _this4.off("close", onclose); + + _this4.off("upgrading", onupgrade); + }; + + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + + }, { + key: "onOpen", + value: function onOpen() { + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); // we check for `readyState` in case an `open` + // listener already closed the socket + + if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) { + var i = 0; + var l = this.upgrades.length; + + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + + }, { + key: "onPacket", + value: function onPacket(packet) { + if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { + this.emitReserved("packet", packet); // Socket is live - any packet counts + + this.emitReserved("heartbeat"); + + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + + case "error": + var err = new Error("server error"); // @ts-ignore + + err.code = packet.data; + this.onError(err); + break; + + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + + }, { + key: "onHandshake", + value: function onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.maxPayload = data.maxPayload; + this.onOpen(); // In case open handler closes socket + + if ("closed" === this.readyState) return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + + }, { + key: "resetPingTimeout", + value: function resetPingTimeout() { + var _this5 = this; + + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(function () { + _this5.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + + }, { + key: "onDrain", + value: function onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + + this.prevBufferLen = 0; + + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + + }, { + key: "flush", + value: function flush() { + if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { + var packets = this.getWritablePackets(); + this.transport.send(packets); // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + + this.prevBufferLen = packets.length; + this.emitReserved("flush"); + } + } + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + + }, { + key: "getWritablePackets", + value: function getWritablePackets() { + var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1; + + if (!shouldCheckPayloadSize) { + return this.writeBuffer; + } + + var payloadSize = 1; // first packet type + + for (var i = 0; i < this.writeBuffer.length; i++) { + var data = this.writeBuffer[i].data; + + if (data) { + payloadSize += byteLength(data); + } + + if (i > 0 && payloadSize > this.maxPayload) { + return this.writeBuffer.slice(0, i); + } + + payloadSize += 2; // separator + packet type + } + + return this.writeBuffer; + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + + }, { + key: "write", + value: function write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + }, { + key: "send", + value: function send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + + }, { + key: "sendPacket", + value: function sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + + if ("function" === typeof options) { + fn = options; + options = null; + } + + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + + options = options || {}; + options.compress = false !== options.compress; + var packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + + }, { + key: "close", + value: function close() { + var _this6 = this; + + var close = function close() { + _this6.onClose("forced close"); + + _this6.transport.close(); + }; + + var cleanupAndClose = function cleanupAndClose() { + _this6.off("upgrade", cleanupAndClose); + + _this6.off("upgradeError", cleanupAndClose); + + close(); + }; + + var waitForUpgrade = function waitForUpgrade() { + // wait for upgrade to finish since we can't send packets while pausing a transport + _this6.once("upgrade", cleanupAndClose); + + _this6.once("upgradeError", cleanupAndClose); + }; + + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + + if (this.writeBuffer.length) { + this.once("drain", function () { + if (_this6.upgrading) { + waitForUpgrade(); + } else { + close(); + } + }); + } else if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + } + + return this; + } + /** + * Called upon transport error + * + * @api private + */ + + }, { + key: "onError", + value: function onError(err) { + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + + }, { + key: "onClose", + value: function onClose(reason, description) { + if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport + + this.transport.removeAllListeners("close"); // ensure transport won't stay open + + this.transport.close(); // ignore further transport communication + + this.transport.removeAllListeners(); + + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } // set ready state + + + this.readyState = "closed"; // clear session id + + this.id = null; // emit close event + + this.emitReserved("close", reason, description); // clean buffers after, so users can still + // grab the buffers on `close` event + + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + + }, { + key: "filterUpgrades", + value: function filterUpgrades(upgrades) { + var filteredUpgrades = []; + var i = 0; + var j = upgrades.length; + + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]); + } + + return filteredUpgrades; + } + }]); + + return Socket; + }(Emitter); + Socket.protocol = protocol; + + var browserEntrypoint = (function (uri, opts) { + return new Socket(uri, opts); + }); + + return browserEntrypoint; + +})); +//# sourceMappingURL=engine.io.js.map diff --git a/node_modules/engine.io-client/dist/engine.io.js.map b/node_modules/engine.io-client/dist/engine.io.js.map new file mode 100644 index 0000000..d866b6a --- /dev/null +++ b/node_modules/engine.io-client/dist/engine.io.js.map @@ -0,0 +1 @@ +{"version":3,"file":"engine.io.js","sources":["../node_modules/engine.io-parser/build/esm/commons.js","../node_modules/engine.io-parser/build/esm/encodePacket.browser.js","../node_modules/@socket.io/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/engine.io-parser/build/esm/decodePacket.browser.js","../node_modules/engine.io-parser/build/esm/index.js","../node_modules/@socket.io/component-emitter/index.mjs","../build/esm/globalThis.browser.js","../build/esm/util.js","../build/esm/transport.js","../build/esm/contrib/yeast.js","../build/esm/contrib/parseqs.js","../build/esm/contrib/has-cors.js","../build/esm/transports/xmlhttprequest.browser.js","../build/esm/transports/polling.js","../build/esm/transports/websocket-constructor.browser.js","../build/esm/transports/websocket.js","../build/esm/transports/index.js","../build/esm/contrib/parseuri.js","../build/esm/socket.js","../build/esm/browser-entrypoint.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export const globalThisShim = (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import { globalThisShim as globalThis } from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nexport function XHR(opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport { XHR as XMLHttpRequest } from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import { globalThisShim as globalThis } from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return !!WebSocket;\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","import { Socket } from \"./socket.js\";\nexport default (uri, opts) => new Socket(uri, opts);\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","isView","obj","buffer","encodePacket","supportsBinary","callback","encodeBlobAsBase64","fileReader","FileReader","onload","content","result","split","readAsDataURL","i","decode","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","packetType","length","decoded","base64","SEPARATOR","String","fromCharCode","encodePayload","packets","encodedPackets","Array","count","packet","join","decodePayload","encodedPayload","decodedPacket","push","protocol","Emitter","mixin","on","addEventListener","event","fn","_callbacks","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","callbacks","cb","splice","emit","args","slice","len","emitReserved","listeners","hasListeners","globalThisShim","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","BASE64_OVERHEAD","byteLength","utf8Length","Math","ceil","size","str","c","l","charCodeAt","TransportError","reason","description","context","Error","Transport","writable","query","readyState","socket","doOpen","doClose","onClose","write","onPacket","details","alphabet","map","seed","prev","encode","num","encoded","floor","yeast","now","Date","encodeURIComponent","qs","qry","pairs","pair","decodeURIComponent","value","XMLHttpRequest","err","hasCORS","XHR","xdomain","e","concat","empty","hasXHR2","xhr","responseType","Polling","polling","location","isSSL","port","xd","hostname","xs","secure","forceBase64","poll","onPause","pause","total","doPoll","onOpen","close","doWrite","schema","timestampRequests","timestampParam","sid","b64","Number","encodedQuery","ipv6","indexOf","path","Request","uri","req","request","method","xhrStatus","onError","onData","pollXhr","async","undefined","xscheme","open","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","onLoad","send","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","terminationEvent","nextTick","isPromiseAvailable","Promise","resolve","then","WebSocket","MozWebSocket","usingBrowserWebSocket","defaultBinaryType","isReactNative","navigator","product","toLowerCase","WS","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","transports","websocket","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","queryKey","regx","names","substr","$0","$1","$2","Socket","writeBuffer","prevBufferLen","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","name","EIO","priorWebsocketSuccess","createTransport","shift","setTransport","onDrain","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","probe","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","shouldCheckPayloadSize","payloadSize","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA,IAAMA,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAc,IAAd,CAArB;;EACAF,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,OAAD,CAAZ,GAAwB,GAAxB;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,SAAD,CAAZ,GAA0B,GAA1B;EACAA,YAAY,CAAC,SAAD,CAAZ,GAA0B,GAA1B;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACA,IAAMG,oBAAoB,GAA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AC3CA,UAAAA,mBAAmB,CAAC,SAAD,EAAY,KAAKyN,oBAAjB,EAAuC,KAAvC,CAAnB;EACH,SAX8B;;;EAa/B,aAAKvK,UAAL,GAAkB,QAAlB,CAb+B;;EAe/B,aAAKiK,EAAL,GAAU,IAAV,CAf+B;;EAiB/B,aAAK3M,YAAL,CAAkB,OAAlB,EAA2BmC,MAA3B,EAAmCC,WAAnC,EAjB+B;EAmB/B;;EACA,aAAK6J,WAAL,GAAmB,EAAnB;EACA,aAAKC,aAAL,GAAqB,CAArB;EACH;EACJ;EACD;EACJ;EACA;EACA;EACA;EACA;EACA;;EAhjBA;EAAA;EAAA,mCAijBmBU,QAjjBnB,EAijB6B;EACrB,UAAMsC,gBAAgB,GAAG,EAAzB;EACA,UAAInS,CAAC,GAAG,CAAR;EACA,UAAMoS,CAAC,GAAGvC,QAAQ,CAACnP,MAAnB;;EACA,aAAOV,CAAC,GAAGoS,CAAX,EAAcpS,CAAC,EAAf,EAAmB;EACf,YAAI,CAAC,KAAK2N,UAAL,CAAgBjE,OAAhB,CAAwBmG,QAAQ,CAAC7P,CAAD,CAAhC,CAAL,EACImS,gBAAgB,CAACzQ,IAAjB,CAAsBmO,QAAQ,CAAC7P,CAAD,CAA9B;EACP;;EACD,aAAOmS,gBAAP;EACH;EA1jBL;;EAAA;EAAA,EAA4BvQ,OAA5B;EA4jBAqN,MAAM,CAACtN,QAAP,GAAkBA,QAAlB;;ACjkBA,2BAAe,UAACkI,GAAD,EAAM1F,IAAN;EAAA,SAAe,IAAI8K,MAAJ,CAAWpF,GAAX,EAAgB1F,IAAhB,CAAf;EAAA,CAAf;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/engine.io-client/dist/engine.io.min.js b/node_modules/engine.io-client/dist/engine.io.min.js new file mode 100644 index 0000000..0f3ccc1 --- /dev/null +++ b/node_modules/engine.io-client/dist/engine.io.min.js @@ -0,0 +1,7 @@ +/*! + * Engine.IO v6.2.2 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).eio=e()}(this,(function(){"use strict";function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){for(var r=0;r1?{type:v[r],data:t.substring(1)}:{type:v[r]}:m},E=function(t,e){if(x){var r=function(t){var e,r,n,o,i,s=.75*t.length,a=t.length,u=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);var c=new ArrayBuffer(s),p=new Uint8Array(c);for(e=0;e>4,p[u++]=(15&n)<<4|o>>2,p[u++]=(3&o)<<6|63&i;return c}(t);return P(r,e)}return{base64:!0,data:t}},P=function(t,e){return"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t},B=String.fromCharCode(30);function C(t){if(t)return function(t){for(var e in C.prototype)t[e]=C.prototype[e];return t}(t)}C.prototype.on=C.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},C.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},C.prototype.off=C.prototype.removeListener=C.prototype.removeAllListeners=C.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o1?e-1:0),n=1;n0);return e}function X(){var t=N(+new Date);return t!==U?(I=0,U=t):t+"."+N(I++)}for(;W<64;W++)M[D[W]]=W;function $(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e}function z(t){for(var e={},r=t.split("&"),n=0,o=r.length;n0&&void 0!==arguments[0]?arguments[0]:{};return o(t,{xd:this.xd,xs:this.xs},this.opts),new Z(this.uri(),t)}},{key:"doWrite",value:function(t,e){var r=this,n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(function(t,e){r.onError("xhr post error",t,e)}))}},{key:"doPoll",value:function(){var t=this,e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(function(e,r){t.onError("xhr poll error",e,r)})),this.pollXhr=e}},{key:"name",get:function(){return"polling"}}]),s}(F),Z=function(t){i(o,t);var r=f(o);function o(t,n){var i;return e(this,o),_(h(i=r.call(this)),n),i.opts=n,i.method=n.method||"GET",i.uri=t,i.async=!1!==n.async,i.data=void 0!==n.data?n.data:null,i.create(),i}return n(o,[{key:"create",value:function(){var t=this,e=q(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;var r=this.xhr=new J(e);try{r.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders)for(var n in r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(n)&&r.setRequestHeader(n,this.opts.extraHeaders[n])}catch(t){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{r.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=function(){4===r.readyState&&(200===r.status||1223===r.status?t.onLoad():t.setTimeoutFn((function(){t.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((function(){t.onError(e)}),0)}"undefined"!=typeof document&&(this.index=o.requestsCount++,o.requests[this.index]=this)}},{key:"onError",value:function(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=K,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete o.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),o}(C);if(Z.requestsCount=0,Z.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",tt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in L?"pagehide":"unload",tt,!1)}function tt(){for(var t in Z.requests)Z.requests.hasOwnProperty(t)&&Z.requests[t].abort()}var et="function"==typeof Promise&&"function"==typeof Promise.resolve?function(t){return Promise.resolve().then(t)}:function(t,e){return e(t,0)},rt=L.WebSocket||L.MozWebSocket,nt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),ot=function(t){i(o,t);var r=f(o);function o(t){var n;return e(this,o),(n=r.call(this,t)).supportsBinary=!t.forceBase64,n}return n(o,[{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,r=nt?{}:q(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=nt?new rt(t,e,r):e?new rt(t,e):new rt(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen()},this.ws.onclose=function(e){return t.onClose({description:"websocket connection closed",context:e})},this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError("websocket error",e)}}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var r=function(r){var n=t[r],o=r===t.length-1;k(n,e.supportsBinary,(function(t){try{e.ws.send(t)}catch(t){}o&&et((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},n=0;n1&&void 0!==arguments[1]?arguments[1]:{};return e(this,a),n=s.call(this),r&&"object"===t(r)&&(i=r,r=null),r?(r=ut(r),i.hostname=r.host,i.secure="https"===r.protocol||"wss"===r.protocol,i.port=r.port,r.query&&(i.query=r.query)):i.host&&(i.hostname=ut(i.host).host),_(h(n),i),n.secure=null!=i.secure?i.secure:"undefined"!=typeof location&&"https:"===location.protocol,i.hostname&&!i.port&&(i.port=n.secure?"443":"80"),n.hostname=i.hostname||("undefined"!=typeof location?location.hostname:"localhost"),n.port=i.port||("undefined"!=typeof location&&location.port?location.port:n.secure?"443":"80"),n.transports=i.transports||["polling","websocket"],n.readyState="",n.writeBuffer=[],n.prevBufferLen=0,n.opts=o({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},i),n.opts.path=n.opts.path.replace(/\/$/,"")+"/","string"==typeof n.opts.query&&(n.opts.query=z(n.opts.query)),n.id=null,n.upgrades=null,n.pingInterval=null,n.pingTimeout=null,n.pingTimeoutTimer=null,"function"==typeof addEventListener&&(n.opts.closeOnBeforeunload&&addEventListener("beforeunload",(function(){n.transport&&(n.transport.removeAllListeners(),n.transport.close())}),!1),"localhost"!==n.hostname&&(n.offlineEventListener=function(){n.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",n.offlineEventListener,!1))),n.open(),n}return n(a,[{key:"createTransport",value:function(t){var e=o({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);var r=o({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new it[t](r)}},{key:"open",value:function(){var t,e=this;if(this.opts.rememberUpgrade&&a.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((function(){e.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}},{key:"setTransport",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(function(t){return e.onClose("transport close",t)}))}},{key:"probe",value:function(t){var e=this,r=this.createTransport(t),n=!1;a.priorWebsocketSuccess=!1;var o=function(){n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",(function(t){if(!n)if("pong"===t.type&&"probe"===t.data){if(e.upgrading=!0,e.emitReserved("upgrading",r),!r)return;a.priorWebsocketSuccess="websocket"===r.name,e.transport.pause((function(){n||"closed"!==e.readyState&&(h(),e.setTransport(r),r.send([{type:"upgrade"}]),e.emitReserved("upgrade",r),r=null,e.upgrading=!1,e.flush())}))}else{var o=new Error("probe error");o.transport=r.name,e.emitReserved("upgradeError",o)}})))};function i(){n||(n=!0,h(),r.close(),r=null)}var s=function(t){var n=new Error("probe error: "+t);n.transport=r.name,i(),e.emitReserved("upgradeError",n)};function u(){s("transport closed")}function c(){s("socket closed")}function p(t){r&&t.name!==r.name&&i()}var h=function(){r.removeListener("open",o),r.removeListener("error",s),r.removeListener("close",u),e.off("close",c),e.off("upgrading",p)};r.once("open",o),r.once("error",s),r.once("close",u),this.once("close",c),this.once("upgrading",p),r.open()}},{key:"onOpen",value:function(){if(this.readyState="open",a.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t1))return this.writeBuffer;for(var t,e=1,r=0;r=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}return this.writeBuffer}},{key:"write",value:function(t,e,r){return this.sendPacket("message",t,e,r),this}},{key:"send",value:function(t,e,r){return this.sendPacket("message",t,e,r),this}},{key:"sendPacket",value:function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}}},{key:"close",value:function(){var t=this,e=function(){t.onClose("forced close"),t.transport.close()},r=function r(){t.off("upgrade",r),t.off("upgradeError",r),e()},n=function(){t.once("upgrade",r),t.once("upgradeError",r)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){t.upgrading?n():e()})):this.upgrading?n():e()),this}},{key:"onError",value:function(t){a.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}},{key:"onClose",value:function(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(t){for(var e=[],r=0,n=t.length;r {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export const globalThisShim = (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import { globalThisShim as globalThis } from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nexport function XHR(opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport { XHR as XMLHttpRequest } from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport { globalThisShim as globalThis } from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import { globalThisShim as globalThis } from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return !!WebSocket;\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","import { Socket } from \"./socket.js\";\nexport default (uri, opts) => new Socket(uri, opts);\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","encodePacket","supportsBinary","callback","obj","encodeBlobAsBase64","isView","buffer","fileReader","FileReader","onload","content","result","split","readAsDataURL","chars","lookup","Uint8Array","i","length","charCodeAt","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","decoded","base64","encoded1","encoded2","encoded3","encoded4","bufferLength","len","p","arraybuffer","bytes","decode","SEPARATOR","String","fromCharCode","Emitter","mixin","on","addEventListener","event","fn","_callbacks","this","push","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","cb","callbacks","splice","emit","args","Array","slice","emitReserved","listeners","hasListeners","globalThisShim","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","prev","TransportError","reason","description","context","Error","Transport","writable","query","readyState","socket","doOpen","doClose","onClose","packets","write","packet","onPacket","details","alphabet","map","seed","encode","num","encoded","Math","floor","yeast","now","Date","str","encodeURIComponent","qs","qry","pairs","l","pair","decodeURIComponent","value","XMLHttpRequest","err","hasCORS","XHR","xdomain","e","concat","join","empty","hasXHR2","responseType","Polling","polling","location","isSSL","protocol","port","xd","hostname","xs","secure","forceBase64","poll","onPause","pause","_this2","total","doPoll","encodedPayload","encodedPackets","decodedPacket","decodePayload","_this3","onOpen","close","_this4","count","encodePayload","_this5","doWrite","schema","timestampRequests","timestampParam","sid","b64","Number","encodedQuery","indexOf","path","Request","uri","req","request","method","xhrStatus","_this6","onError","onData","_this7","pollXhr","async","undefined","xscheme","xhr","open","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","_this9","onLoad","send","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","nextTick","Promise","resolve","then","WebSocket","MozWebSocket","isReactNative","navigator","product","toLowerCase","WS","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","transports","websocket","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","regx","names","substr","queryKey","$0","$1","$2","Socket","_this","writeBuffer","prevBufferLen","_extends","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","name","EIO","priorWebsocketSuccess","createTransport","shift","setTransport","onDrain","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","probe","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","payloadSize","c","utf8Length","ceil","byteLength","size","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j"],"mappings":";;;;;29FAAA,IAAMA,EAAeC,OAAOC,OAAO,MACnCF,EAAY,KAAW,IACvBA,EAAY,MAAY,IACxBA,EAAY,KAAW,IACvBA,EAAY,KAAW,IACvBA,EAAY,QAAc,IAC1BA,EAAY,QAAc,IAC1BA,EAAY,KAAW,IACvB,IAAMG,EAAuBF,OAAOC,OAAO,MAC3CD,OAAOG,KAAKJ,GAAcK,SAAQ,SAAAC,GAC9BH,EAAqBH,EAAaM,IAAQA,KCN9C,IDQA,IAAMC,EAAe,CAAEC,KAAM,QAASC,KAAM,gBEXtCC,EAAiC,mBAATC,MACT,oBAATA,MACqC,6BAAzCV,OAAOW,UAAUC,SAASC,KAAKH,MACjCI,EAA+C,mBAAhBC,YAO/BC,EAAe,WAAiBC,EAAgBC,OALvCC,EAKSZ,IAAAA,KAAMC,IAAAA,YACtBC,GAAkBD,aAAgBE,KAC9BO,EACOC,EAASV,GAGTY,EAAmB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,KAAKwO,sBAAsB,QAGzDvL,WAAa,cAEbiL,GAAK,UAELlN,aAAa,QAAS0B,EAAQC,QAG9B4K,YAAc,QACdC,cAAgB,0CAUdW,WACL0C,EAAmB,GACrB7S,EAAI,EACF8S,EAAI3C,EAASlQ,OACZD,EAAI8S,EAAG9S,KACLgC,KAAK+L,WAAWjE,QAAQqG,EAASnQ,KAClC6S,EAAiB5Q,KAAKkO,EAASnQ,WAEhC6S,SAzjBapR,GA4jB5B4N,GAAOvH,SdpiBiB,kBe7BRmC,EAAK/F,UAAS,IAAImL,GAAOpF,EAAK/F"} \ No newline at end of file diff --git a/node_modules/engine.io-client/package.json b/node_modules/engine.io-client/package.json new file mode 100644 index 0000000..3136e1a --- /dev/null +++ b/node_modules/engine.io-client/package.json @@ -0,0 +1,104 @@ +{ + "name": "engine.io-client", + "description": "Client for the realtime Engine", + "license": "MIT", + "version": "6.2.2", + "main": "./build/cjs/index.js", + "module": "./build/esm/index.js", + "exports": { + "./package.json": "./package.json", + "./dist/engine.io.esm.min.js": "./dist/engine.io.esm.min.js", + "./dist/engine.io.js": "./dist/engine.io.js", + "./dist/engine.io.min.js": "./dist/engine.io.min.js", + ".": { + "import": { + "node": "./build/esm-debug/index.js", + "default": "./build/esm/index.js" + }, + "require": "./build/cjs/index.js" + } + }, + "types": "build/esm/index.d.ts", + "homepage": "https://github.com/socketio/engine.io-client", + "contributors": [ + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Vladimir Dronnikov", + "email": "dronnikov@gmail.com" + }, + { + "name": "Christoph Dorn", + "web": "https://github.com/cadorn" + }, + { + "name": "Mark Mokryn", + "email": "mokesmokes@gmail.com" + } + ], + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3", + "xmlhttprequest-ssl": "~2.0.0" + }, + "devDependencies": { + "@babel/core": "^7.12.9", + "@babel/plugin-transform-object-assign": "^7.12.1", + "@babel/preset-env": "^7.12.7", + "@rollup/plugin-babel": "^5.3.0", + "@rollup/plugin-commonjs": "^21.0.0", + "@rollup/plugin-node-resolve": "^13.0.5", + "@sinonjs/fake-timers": "^7.1.2", + "@types/mocha": "^9.0.0", + "@types/node": "^16.10.1", + "@types/sinonjs__fake-timers": "^6.0.3", + "babel-loader": "^8.2.2", + "blob": "0.0.5", + "engine.io": "^6.2.0-alpha.1", + "expect.js": "^0.3.1", + "express": "^4.17.1", + "mocha": "^3.2.0", + "prettier": "^1.19.1", + "rollup": "^2.58.0", + "rollup-plugin-terser": "^7.0.2", + "socket.io-browsers": "~1.0.4", + "typescript": "^4.4.3", + "webpack": "^4.44.2", + "webpack-cli": "^3.3.12", + "webpack-remove-debug": "^0.1.0", + "zuul": "~3.11.1", + "zuul-builder-webpack": "^1.2.0", + "zuul-ngrok": "4.0.0" + }, + "scripts": { + "compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh", + "test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi", + "test:node": "mocha --bail --reporter dot --require test/support/server.js test/index.js", + "test:browser": "zuul test/index.js", + "build": "rollup -c support/rollup.config.umd.js && rollup -c support/rollup.config.esm.js", + "format:check": "prettier --check 'lib/**/*.ts' 'test/**/*.js' 'support/**/*.js'", + "format:fix": "prettier --write 'lib/**/*.ts' 'test/**/*.js' 'support/**/*.js'", + "prepack": "npm run compile" + }, + "browser": { + "./test/node.js": false, + "./build/esm/transports/xmlhttprequest.js": "./build/esm/transports/xmlhttprequest.browser.js", + "./build/esm/transports/websocket-constructor.js": "./build/esm/transports/websocket-constructor.browser.js", + "./build/esm/globalThis.js": "./build/esm/globalThis.browser.js", + "./build/cjs/transports/xmlhttprequest.js": "./build/cjs/transports/xmlhttprequest.browser.js", + "./build/cjs/transports/websocket-constructor.js": "./build/cjs/transports/websocket-constructor.browser.js", + "./build/cjs/globalThis.js": "./build/cjs/globalThis.browser.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/socketio/engine.io-client.git" + }, + "files": [ + "build/", + "dist/" + ] +} diff --git a/node_modules/engine.io-parser/LICENSE b/node_modules/engine.io-parser/LICENSE new file mode 100644 index 0000000..d8fdaec --- /dev/null +++ b/node_modules/engine.io-parser/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Guillermo Rauch (@rauchg) + +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/node_modules/engine.io-parser/Readme.md b/node_modules/engine.io-parser/Readme.md new file mode 100644 index 0000000..b109650 --- /dev/null +++ b/node_modules/engine.io-parser/Readme.md @@ -0,0 +1,158 @@ + +# engine.io-parser + +[![Build Status](https://github.com/socketio/engine.io-parser/workflows/CI/badge.svg?branch=main)](https://github.com/socketio/engine.io-parser/actions) +[![NPM version](https://badge.fury.io/js/engine.io-parser.svg)](https://npmjs.com/package/engine.io-parser) + +This is the JavaScript parser for the engine.io protocol encoding, +shared by both +[engine.io-client](https://github.com/socketio/engine.io-client) and +[engine.io](https://github.com/socketio/engine.io). + +## How to use + +### Standalone + +The parser can encode/decode packets, payloads, and payloads as binary +with the following methods: `encodePacket`, `decodePacket`, `encodePayload`, +`decodePayload`. + +Example: + +```js +const parser = require("engine.io-parser"); +const data = Buffer.from([ 1, 2, 3, 4 ]); + +parser.encodePacket({ type: "message", data }, encoded => { + const decodedData = parser.decodePacket(encoded); // decodedData === data +}); +``` + +### With browserify + +Engine.IO Parser is a commonjs module, which means you can include it by using +`require` on the browser and package using [browserify](http://browserify.org/): + +1. install the parser package + + ```shell + npm install engine.io-parser + ``` + +1. write your app code + + ```js + const parser = require("engine.io-parser"); + + const testBuffer = new Int8Array(10); + for (let i = 0; i < testBuffer.length; i++) testBuffer[i] = i; + + const packets = [{ type: "message", data: testBuffer.buffer }, { type: "message", data: "hello" }]; + + parser.encodePayload(packets, encoded => { + parser.decodePayload(encoded, + (packet, index, total) => { + const isLast = index + 1 == total; + if (!isLast) { + const buffer = new Int8Array(packet.data); // testBuffer + } else { + const message = packet.data; // "hello" + } + }); + }); + ``` + +1. build your app bundle + + ```bash + $ browserify app.js > bundle.js + ``` + +1. include on your page + + ```html + + ``` + +## Features + +- Runs on browser and node.js seamlessly +- Runs inside HTML5 WebWorker +- Can encode and decode packets + - Encodes from/to ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer in Node + +## API + +Note: `cb(type)` means the type is a callback function that contains a parameter of type `type` when called. + +### Node + +- `encodePacket` + - Encodes a packet. + - **Parameters** + - `Object`: the packet to encode, has `type` and `data`. + - `data`: can be a `String`, `Number`, `Buffer`, `ArrayBuffer` + - `Boolean`: binary support + - `Function`: callback, returns the encoded packet (`cb(String)`) +- `decodePacket` + - Decodes a packet. Data also available as an ArrayBuffer if requested. + - Returns data as `String` or (`Blob` on browser, `ArrayBuffer` on Node) + - **Parameters** + - `String` | `ArrayBuffer`: the packet to decode, has `type` and `data` + - `String`: optional, the binary type + +- `encodePayload` + - Encodes multiple messages (payload). + - If any contents are binary, they will be encoded as base64 strings. Base64 + encoded strings are marked with a b before the length specifier + - **Parameters** + - `Array`: an array of packets + - `Function`: callback, returns the encoded payload (`cb(String)`) +- `decodePayload` + - Decodes data when a payload is maybe expected. Possible binary contents are + decoded from their base64 representation. + - **Parameters** + - `String`: the payload + - `Function`: callback, returns (cb(`Object`: packet, `Number`:packet index, `Number`:packet total)) + +## Tests + +Standalone tests can be run with `npm test` which will run the node.js tests. + +Browser tests are run using [zuul](https://github.com/defunctzombie/zuul). +(You must have zuul setup with a saucelabs account.) + +You can run the tests locally using the following command: + +``` +npm run test:browser +``` + +## Support + +The support channels for `engine.io-parser` are the same as `socket.io`: + - irc.freenode.net **#socket.io** + - [Github Discussions](https://github.com/socketio/socket.io/discussions) + - [Website](https://socket.io) + +## Development + +To contribute patches, run tests or benchmarks, make sure to clone the +repository: + +```bash +git clone git://github.com/socketio/engine.io-parser.git +``` + +Then: + +```bash +cd engine.io-parser +npm ci +``` + +See the `Tests` section above for how to run tests before submitting any patches. + +## License + +MIT diff --git a/node_modules/engine.io-parser/build/cjs/commons.js b/node_modules/engine.io-parser/build/cjs/commons.js new file mode 100644 index 0000000..4a0b629 --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/commons.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ERROR_PACKET = exports.PACKET_TYPES_REVERSE = exports.PACKET_TYPES = void 0; +const PACKET_TYPES = Object.create(null); // no Map = no polyfill +exports.PACKET_TYPES = PACKET_TYPES; +PACKET_TYPES["open"] = "0"; +PACKET_TYPES["close"] = "1"; +PACKET_TYPES["ping"] = "2"; +PACKET_TYPES["pong"] = "3"; +PACKET_TYPES["message"] = "4"; +PACKET_TYPES["upgrade"] = "5"; +PACKET_TYPES["noop"] = "6"; +const PACKET_TYPES_REVERSE = Object.create(null); +exports.PACKET_TYPES_REVERSE = PACKET_TYPES_REVERSE; +Object.keys(PACKET_TYPES).forEach(key => { + PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; +}); +const ERROR_PACKET = { type: "error", data: "parser error" }; +exports.ERROR_PACKET = ERROR_PACKET; diff --git a/node_modules/engine.io-parser/build/cjs/contrib/base64-arraybuffer.js b/node_modules/engine.io-parser/build/cjs/contrib/base64-arraybuffer.js new file mode 100644 index 0000000..d5801d2 --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/contrib/base64-arraybuffer.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decode = exports.encode = void 0; +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +// Use a lookup table to find the index. +const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); +for (let i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; +} +const encode = (arraybuffer) => { + let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ''; + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } + else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + return base64; +}; +exports.encode = encode; +const decode = (base64) => { + let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return arraybuffer; +}; +exports.decode = decode; diff --git a/node_modules/engine.io-parser/build/cjs/decodePacket.browser.js b/node_modules/engine.io-parser/build/cjs/decodePacket.browser.js new file mode 100644 index 0000000..fb8b7ab --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/decodePacket.browser.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const base64_arraybuffer_js_1 = require("./contrib/base64-arraybuffer.js"); +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const decodePacket = (encodedPacket, binaryType) => { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + const type = encodedPacket.charAt(0); + if (type === "b") { + return { + type: "message", + data: decodeBase64Packet(encodedPacket.substring(1), binaryType) + }; + } + const packetType = commons_js_1.PACKET_TYPES_REVERSE[type]; + if (!packetType) { + return commons_js_1.ERROR_PACKET; + } + return encodedPacket.length > 1 + ? { + type: commons_js_1.PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } + : { + type: commons_js_1.PACKET_TYPES_REVERSE[type] + }; +}; +const decodeBase64Packet = (data, binaryType) => { + if (withNativeArrayBuffer) { + const decoded = (0, base64_arraybuffer_js_1.decode)(data); + return mapBinary(decoded, binaryType); + } + else { + return { base64: true, data }; // fallback for old browsers + } +}; +const mapBinary = (data, binaryType) => { + switch (binaryType) { + case "blob": + return data instanceof ArrayBuffer ? new Blob([data]) : data; + case "arraybuffer": + default: + return data; // assuming the data is already an ArrayBuffer + } +}; +exports.default = decodePacket; diff --git a/node_modules/engine.io-parser/build/cjs/decodePacket.js b/node_modules/engine.io-parser/build/cjs/decodePacket.js new file mode 100644 index 0000000..2dbe0f8 --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/decodePacket.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const decodePacket = (encodedPacket, binaryType) => { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + const type = encodedPacket.charAt(0); + if (type === "b") { + const buffer = Buffer.from(encodedPacket.substring(1), "base64"); + return { + type: "message", + data: mapBinary(buffer, binaryType) + }; + } + if (!commons_js_1.PACKET_TYPES_REVERSE[type]) { + return commons_js_1.ERROR_PACKET; + } + return encodedPacket.length > 1 + ? { + type: commons_js_1.PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } + : { + type: commons_js_1.PACKET_TYPES_REVERSE[type] + }; +}; +const mapBinary = (data, binaryType) => { + const isBuffer = Buffer.isBuffer(data); + switch (binaryType) { + case "arraybuffer": + return isBuffer ? toArrayBuffer(data) : data; + case "nodebuffer": + default: + return data; // assuming the data is already a Buffer + } +}; +const toArrayBuffer = (buffer) => { + const arrayBuffer = new ArrayBuffer(buffer.length); + const view = new Uint8Array(arrayBuffer); + for (let i = 0; i < buffer.length; i++) { + view[i] = buffer[i]; + } + return arrayBuffer; +}; +exports.default = decodePacket; diff --git a/node_modules/engine.io-parser/build/cjs/encodePacket.browser.js b/node_modules/engine.io-parser/build/cjs/encodePacket.browser.js new file mode 100644 index 0000000..b06ec9b --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/encodePacket.browser.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + Object.prototype.toString.call(Blob) === "[object BlobConstructor]"); +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +// ArrayBuffer.isView method is not defined in IE10 +const isView = obj => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj && obj.buffer instanceof ArrayBuffer; +}; +const encodePacket = ({ type, data }, supportsBinary, callback) => { + if (withNativeBlob && data instanceof Blob) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(data, callback); + } + } + else if (withNativeArrayBuffer && + (data instanceof ArrayBuffer || isView(data))) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(new Blob([data]), callback); + } + } + // plain string + return callback(commons_js_1.PACKET_TYPES[type] + (data || "")); +}; +const encodeBlobAsBase64 = (data, callback) => { + const fileReader = new FileReader(); + fileReader.onload = function () { + const content = fileReader.result.split(",")[1]; + callback("b" + content); + }; + return fileReader.readAsDataURL(data); +}; +exports.default = encodePacket; diff --git a/node_modules/engine.io-parser/build/cjs/encodePacket.js b/node_modules/engine.io-parser/build/cjs/encodePacket.js new file mode 100644 index 0000000..bd81d02 --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/encodePacket.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const commons_js_1 = require("./commons.js"); +const encodePacket = ({ type, data }, supportsBinary, callback) => { + if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + const buffer = toBuffer(data); + return callback(encodeBuffer(buffer, supportsBinary)); + } + // plain string + return callback(commons_js_1.PACKET_TYPES[type] + (data || "")); +}; +const toBuffer = data => { + if (Buffer.isBuffer(data)) { + return data; + } + else if (data instanceof ArrayBuffer) { + return Buffer.from(data); + } + else { + return Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } +}; +// only 'message' packets can contain binary, so the type prefix is not needed +const encodeBuffer = (data, supportsBinary) => { + return supportsBinary ? data : "b" + data.toString("base64"); +}; +exports.default = encodePacket; diff --git a/node_modules/engine.io-parser/build/cjs/index.js b/node_modules/engine.io-parser/build/cjs/index.js new file mode 100644 index 0000000..858f247 --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/index.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodePayload = exports.decodePacket = exports.encodePayload = exports.encodePacket = exports.protocol = void 0; +const encodePacket_js_1 = require("./encodePacket.js"); +exports.encodePacket = encodePacket_js_1.default; +const decodePacket_js_1 = require("./decodePacket.js"); +exports.decodePacket = decodePacket_js_1.default; +const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text +const encodePayload = (packets, callback) => { + // some packets may be added to the array while encoding, so the initial length must be saved + const length = packets.length; + const encodedPackets = new Array(length); + let count = 0; + packets.forEach((packet, i) => { + // force base64 encoding for binary packets + (0, encodePacket_js_1.default)(packet, false, encodedPacket => { + encodedPackets[i] = encodedPacket; + if (++count === length) { + callback(encodedPackets.join(SEPARATOR)); + } + }); + }); +}; +exports.encodePayload = encodePayload; +const decodePayload = (encodedPayload, binaryType) => { + const encodedPackets = encodedPayload.split(SEPARATOR); + const packets = []; + for (let i = 0; i < encodedPackets.length; i++) { + const decodedPacket = (0, decodePacket_js_1.default)(encodedPackets[i], binaryType); + packets.push(decodedPacket); + if (decodedPacket.type === "error") { + break; + } + } + return packets; +}; +exports.decodePayload = decodePayload; +exports.protocol = 4; diff --git a/node_modules/engine.io-parser/build/cjs/package.json b/node_modules/engine.io-parser/build/cjs/package.json new file mode 100644 index 0000000..bdc4dbd --- /dev/null +++ b/node_modules/engine.io-parser/build/cjs/package.json @@ -0,0 +1,8 @@ +{ + "name": "engine.io-parser", + "type": "commonjs", + "browser": { + "./encodePacket.js": "./encodePacket.browser.js", + "./decodePacket.js": "./decodePacket.browser.js" + } +} diff --git a/node_modules/engine.io-parser/build/esm/commons.d.ts b/node_modules/engine.io-parser/build/esm/commons.d.ts new file mode 100644 index 0000000..2eec1dd --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/commons.d.ts @@ -0,0 +1,14 @@ +declare const PACKET_TYPES: any; +declare const PACKET_TYPES_REVERSE: any; +declare const ERROR_PACKET: Packet; +export { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET }; +export declare type PacketType = "open" | "close" | "ping" | "pong" | "message" | "upgrade" | "noop" | "error"; +export declare type RawData = any; +export interface Packet { + type: PacketType; + options?: { + compress: boolean; + }; + data?: RawData; +} +export declare type BinaryType = "nodebuffer" | "arraybuffer" | "blob"; diff --git a/node_modules/engine.io-parser/build/esm/commons.js b/node_modules/engine.io-parser/build/esm/commons.js new file mode 100644 index 0000000..c003b58 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/commons.js @@ -0,0 +1,14 @@ +const PACKET_TYPES = Object.create(null); // no Map = no polyfill +PACKET_TYPES["open"] = "0"; +PACKET_TYPES["close"] = "1"; +PACKET_TYPES["ping"] = "2"; +PACKET_TYPES["pong"] = "3"; +PACKET_TYPES["message"] = "4"; +PACKET_TYPES["upgrade"] = "5"; +PACKET_TYPES["noop"] = "6"; +const PACKET_TYPES_REVERSE = Object.create(null); +Object.keys(PACKET_TYPES).forEach(key => { + PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; +}); +const ERROR_PACKET = { type: "error", data: "parser error" }; +export { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET }; diff --git a/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.d.ts b/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.d.ts new file mode 100644 index 0000000..6e0fa6b --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.d.ts @@ -0,0 +1,2 @@ +export declare const encode: (arraybuffer: ArrayBuffer) => string; +export declare const decode: (base64: string) => ArrayBuffer; diff --git a/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js b/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js new file mode 100644 index 0000000..dd9ba62 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js @@ -0,0 +1,42 @@ +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +// Use a lookup table to find the index. +const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); +for (let i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; +} +export const encode = (arraybuffer) => { + let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ''; + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } + else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + return base64; +}; +export const decode = (base64) => { + let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return arraybuffer; +}; diff --git a/node_modules/engine.io-parser/build/esm/decodePacket.browser.d.ts b/node_modules/engine.io-parser/build/esm/decodePacket.browser.d.ts new file mode 100644 index 0000000..e4045d6 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/decodePacket.browser.d.ts @@ -0,0 +1,3 @@ +import { Packet, BinaryType, RawData } from "./commons.js"; +declare const decodePacket: (encodedPacket: RawData, binaryType?: BinaryType) => Packet; +export default decodePacket; diff --git a/node_modules/engine.io-parser/build/esm/decodePacket.browser.js b/node_modules/engine.io-parser/build/esm/decodePacket.browser.js new file mode 100644 index 0000000..1d8453d --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/decodePacket.browser.js @@ -0,0 +1,49 @@ +import { ERROR_PACKET, PACKET_TYPES_REVERSE } from "./commons.js"; +import { decode } from "./contrib/base64-arraybuffer.js"; +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const decodePacket = (encodedPacket, binaryType) => { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + const type = encodedPacket.charAt(0); + if (type === "b") { + return { + type: "message", + data: decodeBase64Packet(encodedPacket.substring(1), binaryType) + }; + } + const packetType = PACKET_TYPES_REVERSE[type]; + if (!packetType) { + return ERROR_PACKET; + } + return encodedPacket.length > 1 + ? { + type: PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } + : { + type: PACKET_TYPES_REVERSE[type] + }; +}; +const decodeBase64Packet = (data, binaryType) => { + if (withNativeArrayBuffer) { + const decoded = decode(data); + return mapBinary(decoded, binaryType); + } + else { + return { base64: true, data }; // fallback for old browsers + } +}; +const mapBinary = (data, binaryType) => { + switch (binaryType) { + case "blob": + return data instanceof ArrayBuffer ? new Blob([data]) : data; + case "arraybuffer": + default: + return data; // assuming the data is already an ArrayBuffer + } +}; +export default decodePacket; diff --git a/node_modules/engine.io-parser/build/esm/decodePacket.d.ts b/node_modules/engine.io-parser/build/esm/decodePacket.d.ts new file mode 100644 index 0000000..e4045d6 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/decodePacket.d.ts @@ -0,0 +1,3 @@ +import { Packet, BinaryType, RawData } from "./commons.js"; +declare const decodePacket: (encodedPacket: RawData, binaryType?: BinaryType) => Packet; +export default decodePacket; diff --git a/node_modules/engine.io-parser/build/esm/decodePacket.js b/node_modules/engine.io-parser/build/esm/decodePacket.js new file mode 100644 index 0000000..58ca8eb --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/decodePacket.js @@ -0,0 +1,47 @@ +import { ERROR_PACKET, PACKET_TYPES_REVERSE } from "./commons.js"; +const decodePacket = (encodedPacket, binaryType) => { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + const type = encodedPacket.charAt(0); + if (type === "b") { + const buffer = Buffer.from(encodedPacket.substring(1), "base64"); + return { + type: "message", + data: mapBinary(buffer, binaryType) + }; + } + if (!PACKET_TYPES_REVERSE[type]) { + return ERROR_PACKET; + } + return encodedPacket.length > 1 + ? { + type: PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } + : { + type: PACKET_TYPES_REVERSE[type] + }; +}; +const mapBinary = (data, binaryType) => { + const isBuffer = Buffer.isBuffer(data); + switch (binaryType) { + case "arraybuffer": + return isBuffer ? toArrayBuffer(data) : data; + case "nodebuffer": + default: + return data; // assuming the data is already a Buffer + } +}; +const toArrayBuffer = (buffer) => { + const arrayBuffer = new ArrayBuffer(buffer.length); + const view = new Uint8Array(arrayBuffer); + for (let i = 0; i < buffer.length; i++) { + view[i] = buffer[i]; + } + return arrayBuffer; +}; +export default decodePacket; diff --git a/node_modules/engine.io-parser/build/esm/encodePacket.browser.d.ts b/node_modules/engine.io-parser/build/esm/encodePacket.browser.d.ts new file mode 100644 index 0000000..9ca28c8 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/encodePacket.browser.d.ts @@ -0,0 +1,3 @@ +import { Packet, RawData } from "./commons.js"; +declare const encodePacket: ({ type, data }: Packet, supportsBinary: boolean, callback: (encodedPacket: RawData) => void) => void; +export default encodePacket; diff --git a/node_modules/engine.io-parser/build/esm/encodePacket.browser.js b/node_modules/engine.io-parser/build/esm/encodePacket.browser.js new file mode 100644 index 0000000..37d19e4 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/encodePacket.browser.js @@ -0,0 +1,41 @@ +import { PACKET_TYPES } from "./commons.js"; +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + Object.prototype.toString.call(Blob) === "[object BlobConstructor]"); +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +// ArrayBuffer.isView method is not defined in IE10 +const isView = obj => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj && obj.buffer instanceof ArrayBuffer; +}; +const encodePacket = ({ type, data }, supportsBinary, callback) => { + if (withNativeBlob && data instanceof Blob) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(data, callback); + } + } + else if (withNativeArrayBuffer && + (data instanceof ArrayBuffer || isView(data))) { + if (supportsBinary) { + return callback(data); + } + else { + return encodeBlobAsBase64(new Blob([data]), callback); + } + } + // plain string + return callback(PACKET_TYPES[type] + (data || "")); +}; +const encodeBlobAsBase64 = (data, callback) => { + const fileReader = new FileReader(); + fileReader.onload = function () { + const content = fileReader.result.split(",")[1]; + callback("b" + content); + }; + return fileReader.readAsDataURL(data); +}; +export default encodePacket; diff --git a/node_modules/engine.io-parser/build/esm/encodePacket.d.ts b/node_modules/engine.io-parser/build/esm/encodePacket.d.ts new file mode 100644 index 0000000..9ca28c8 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/encodePacket.d.ts @@ -0,0 +1,3 @@ +import { Packet, RawData } from "./commons.js"; +declare const encodePacket: ({ type, data }: Packet, supportsBinary: boolean, callback: (encodedPacket: RawData) => void) => void; +export default encodePacket; diff --git a/node_modules/engine.io-parser/build/esm/encodePacket.js b/node_modules/engine.io-parser/build/esm/encodePacket.js new file mode 100644 index 0000000..789eb74 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/encodePacket.js @@ -0,0 +1,25 @@ +import { PACKET_TYPES } from "./commons.js"; +const encodePacket = ({ type, data }, supportsBinary, callback) => { + if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + const buffer = toBuffer(data); + return callback(encodeBuffer(buffer, supportsBinary)); + } + // plain string + return callback(PACKET_TYPES[type] + (data || "")); +}; +const toBuffer = data => { + if (Buffer.isBuffer(data)) { + return data; + } + else if (data instanceof ArrayBuffer) { + return Buffer.from(data); + } + else { + return Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } +}; +// only 'message' packets can contain binary, so the type prefix is not needed +const encodeBuffer = (data, supportsBinary) => { + return supportsBinary ? data : "b" + data.toString("base64"); +}; +export default encodePacket; diff --git a/node_modules/engine.io-parser/build/esm/index.d.ts b/node_modules/engine.io-parser/build/esm/index.d.ts new file mode 100644 index 0000000..e79de35 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/index.d.ts @@ -0,0 +1,7 @@ +import encodePacket from "./encodePacket.js"; +import decodePacket from "./decodePacket.js"; +import { Packet, PacketType, RawData, BinaryType } from "./commons.js"; +declare const encodePayload: (packets: Packet[], callback: (encodedPayload: string) => void) => void; +declare const decodePayload: (encodedPayload: string, binaryType?: BinaryType) => Packet[]; +export declare const protocol = 4; +export { encodePacket, encodePayload, decodePacket, decodePayload, Packet, PacketType, RawData, BinaryType }; diff --git a/node_modules/engine.io-parser/build/esm/index.js b/node_modules/engine.io-parser/build/esm/index.js new file mode 100644 index 0000000..237a472 --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/index.js @@ -0,0 +1,32 @@ +import encodePacket from "./encodePacket.js"; +import decodePacket from "./decodePacket.js"; +const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text +const encodePayload = (packets, callback) => { + // some packets may be added to the array while encoding, so the initial length must be saved + const length = packets.length; + const encodedPackets = new Array(length); + let count = 0; + packets.forEach((packet, i) => { + // force base64 encoding for binary packets + encodePacket(packet, false, encodedPacket => { + encodedPackets[i] = encodedPacket; + if (++count === length) { + callback(encodedPackets.join(SEPARATOR)); + } + }); + }); +}; +const decodePayload = (encodedPayload, binaryType) => { + const encodedPackets = encodedPayload.split(SEPARATOR); + const packets = []; + for (let i = 0; i < encodedPackets.length; i++) { + const decodedPacket = decodePacket(encodedPackets[i], binaryType); + packets.push(decodedPacket); + if (decodedPacket.type === "error") { + break; + } + } + return packets; +}; +export const protocol = 4; +export { encodePacket, encodePayload, decodePacket, decodePayload }; diff --git a/node_modules/engine.io-parser/build/esm/package.json b/node_modules/engine.io-parser/build/esm/package.json new file mode 100644 index 0000000..6f2c74a --- /dev/null +++ b/node_modules/engine.io-parser/build/esm/package.json @@ -0,0 +1,8 @@ +{ + "name": "engine.io-parser", + "type": "module", + "browser": { + "./encodePacket.js": "./encodePacket.browser.js", + "./decodePacket.js": "./decodePacket.browser.js" + } +} diff --git a/node_modules/engine.io-parser/package.json b/node_modules/engine.io-parser/package.json new file mode 100644 index 0000000..76f7db7 --- /dev/null +++ b/node_modules/engine.io-parser/package.json @@ -0,0 +1,58 @@ +{ + "name": "engine.io-parser", + "description": "Parser for the client for the realtime Engine", + "license": "MIT", + "version": "5.0.4", + "main": "./build/cjs/index.js", + "module": "./build/esm/index.js", + "exports": { + "import": "./build/esm/index.js", + "require": "./build/cjs/index.js" + }, + "types": "build/esm/index.d.ts", + "homepage": "https://github.com/socketio/engine.io-parser", + "devDependencies": { + "@babel/core": "~7.9.6", + "@babel/preset-env": "~7.9.6", + "@types/mocha": "^9.0.0", + "@types/node": "^16.9.6", + "babelify": "^10.0.0", + "benchmark": "^2.1.4", + "expect.js": "0.3.1", + "mocha": "^5.2.0", + "nyc": "~15.0.1", + "prettier": "^1.19.1", + "rimraf": "^3.0.2", + "socket.io-browsers": "^1.0.4", + "ts-node": "^10.2.1", + "tsify": "^5.0.4", + "typescript": "^4.4.3", + "zuul": "3.11.1", + "zuul-ngrok": "4.0.0" + }, + "scripts": { + "compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh", + "test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi", + "test:node": "nyc mocha -r ts-node/register test/index.ts", + "test:browser": "zuul test/index.ts --no-coverage", + "format:check": "prettier --check 'lib/**/*.ts' 'test/**/*.ts'", + "format:fix": "prettier --write 'lib/**/*.ts' 'test/**/*.ts'" + }, + "repository": { + "type": "git", + "url": "git@github.com:socketio/engine.io-parser.git" + }, + "files": [ + "build/" + ], + "browser": { + "./test/node": "./test/browser", + "./build/esm/encodePacket.js": "./build/esm/encodePacket.browser.js", + "./build/esm/decodePacket.js": "./build/esm/decodePacket.browser.js", + "./build/cjs/encodePacket.js": "./build/cjs/encodePacket.browser.js", + "./build/cjs/decodePacket.js": "./build/cjs/decodePacket.browser.js" + }, + "engines": { + "node": ">=10.0.0" + } +} diff --git a/node_modules/fetch-blob/LICENSE b/node_modules/fetch-blob/LICENSE new file mode 100644 index 0000000..0d31723 --- /dev/null +++ b/node_modules/fetch-blob/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 David Frank + +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/node_modules/fetch-blob/README.md b/node_modules/fetch-blob/README.md new file mode 100644 index 0000000..fb3e198 --- /dev/null +++ b/node_modules/fetch-blob/README.md @@ -0,0 +1,106 @@ +# fetch-blob + +[![npm version][npm-image]][npm-url] +[![build status][ci-image]][ci-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] + +A Blob implementation in Node.js, originally from [node-fetch](https://github.com/node-fetch/node-fetch). + +## Installation + +```sh +npm install fetch-blob +``` + +
+ Upgrading from 2x to 3x + + Updating from 2 to 3 should be a breeze since there is not many changes to the blob specification. + The major cause of a major release is coding standards. + - internal WeakMaps was replaced with private fields + - internal Buffer.from was replaced with TextEncoder/Decoder + - internal buffers was replaced with Uint8Arrays + - CommonJS was replaced with ESM + - The node stream returned by calling `blob.stream()` was replaced with whatwg streams + - (Read "Differences from other blobs" for more info.) + +
+ +
+ Differences from other Blobs + + - Unlike NodeJS `buffer.Blob` (Added in: v15.7.0) and browser native Blob this polyfilled version can't be sent via PostMessage + - This blob version is more arbitrary, it can be constructed with blob parts that isn't a instance of itself + it has to look and behave as a blob to be accepted as a blob part. + - The benefit of this is that you can create other types of blobs that don't contain any internal data that has to be read in other ways, such as the `BlobDataItem` created in `from.js` that wraps a file path into a blob-like item and read lazily (nodejs plans to [implement this][fs-blobs] as well) + - The `blob.stream()` is the most noticeable differences. It returns a WHATWG stream now. to keep it as a node stream you would have to do: + + ```js + import {Readable} from 'stream' + const stream = Readable.from(blob.stream()) + ``` +
+ +## Usage + +```js +// Ways to import +// (PS it's dependency free ESM package so regular http-import from CDN works too) +import Blob from 'fetch-blob' +import File from 'fetch-blob/file.js' + +import {Blob} from 'fetch-blob' +import {File} from 'fetch-blob/file.js' + +const {Blob} = await import('fetch-blob') + + +// Ways to read the blob: +const blob = new Blob(['hello, world']) + +await blob.text() +await blob.arrayBuffer() +for await (let chunk of blob.stream()) { ... } +blob.stream().getReader().read() +blob.stream().getReader({mode: 'byob'}).read(view) +``` + +### Blob part backed up by filesystem + +`fetch-blob/from.js` comes packed with tools to convert any filepath into either a Blob or a File +It will not read the content into memory. It will only stat the file for last modified date and file size. + +```js +// The default export is sync and use fs.stat to retrieve size & last modified as a blob +import blobFromSync from 'fetch-blob/from.js' +import {File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync} from 'fetch-blob/from.js' + +const fsFile = fileFromSync('./2-GiB-file.bin', 'application/octet-stream') +const fsBlob = await blobFrom('./2-GiB-file.mp4') + +// Not a 4 GiB memory snapshot, just holds references +// points to where data is located on the disk +const blob = new Blob([fsFile, fsBlob, 'memory', new Uint8Array(10)]) +console.log(blob.size) // ~4 GiB +``` + +`blobFrom|blobFromSync|fileFrom|fileFromSync(path, [mimetype])` + +### Creating Blobs backed up by other async sources +Our Blob & File class are more generic then any other polyfills in the way that it can accept any blob look-a-like item +An example of this is that our blob implementation can be constructed with parts coming from [BlobDataItem](https://github.com/node-fetch/fetch-blob/blob/8ef89adad40d255a3bbd55cf38b88597c1cd5480/from.js#L32) (aka a filepath) or from [buffer.Blob](https://nodejs.org/api/buffer.html#buffer_new_buffer_blob_sources_options), It dose not have to implement all the methods - just enough that it can be read/understood by our Blob implementation. The minium requirements is that it has `Symbol.toStringTag`, `size`, `slice()` and either a `stream()` or a `arrayBuffer()` method. If you then wrap it in our Blob or File `new Blob([blobDataItem])` then you get all of the other methods that should be implemented in a blob or file + +An example of this could be to create a file or blob like item coming from a remote HTTP request. Or from a DataBase + +See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and [tests](https://github.com/node-fetch/fetch-blob/blob/master/test.js) for more details of how to use the Blob. + +[npm-image]: https://flat.badgen.net/npm/v/fetch-blob +[npm-url]: https://www.npmjs.com/package/fetch-blob +[ci-image]: https://github.com/node-fetch/fetch-blob/workflows/CI/badge.svg +[ci-url]: https://github.com/node-fetch/fetch-blob/actions +[codecov-image]: https://flat.badgen.net/codecov/c/github/node-fetch/fetch-blob/master +[codecov-url]: https://codecov.io/gh/node-fetch/fetch-blob +[install-size-image]: https://flat.badgen.net/packagephobia/install/fetch-blob +[install-size-url]: https://packagephobia.now.sh/result?p=fetch-blob +[fs-blobs]: https://github.com/nodejs/node/issues/37340 diff --git a/node_modules/fetch-blob/file.d.ts b/node_modules/fetch-blob/file.d.ts new file mode 100644 index 0000000..d4b89bc --- /dev/null +++ b/node_modules/fetch-blob/file.d.ts @@ -0,0 +1,2 @@ +/** @type {typeof globalThis.File} */ export const File: typeof globalThis.File; +export default File; diff --git a/node_modules/fetch-blob/file.js b/node_modules/fetch-blob/file.js new file mode 100644 index 0000000..7b26538 --- /dev/null +++ b/node_modules/fetch-blob/file.js @@ -0,0 +1,49 @@ +import Blob from './index.js' + +const _File = class File extends Blob { + #lastModified = 0 + #name = '' + + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */// @ts-ignore + constructor (fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`) + } + super(fileBits, options) + + if (options === null) options = {} + + // Simulate WebIDL type casting for NaN value in lastModified option. + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified) + if (!Number.isNaN(lastModified)) { + this.#lastModified = lastModified + } + + this.#name = String(fileName) + } + + get name () { + return this.#name + } + + get lastModified () { + return this.#lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } + + static [Symbol.hasInstance] (object) { + return !!object && object instanceof Blob && + /^(File)$/.test(object[Symbol.toStringTag]) + } +} + +/** @type {typeof globalThis.File} */// @ts-ignore +export const File = _File +export default File diff --git a/node_modules/fetch-blob/from.d.ts b/node_modules/fetch-blob/from.d.ts new file mode 100644 index 0000000..530b99b --- /dev/null +++ b/node_modules/fetch-blob/from.d.ts @@ -0,0 +1,26 @@ +export default blobFromSync; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +export function blobFromSync(path: string, type?: string): Blob; +import File from "./file.js"; +import Blob from "./index.js"; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +export function blobFrom(path: string, type?: string): Promise; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +export function fileFrom(path: string, type?: string): Promise; +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +export function fileFromSync(path: string, type?: string): File; +export { File, Blob }; diff --git a/node_modules/fetch-blob/from.js b/node_modules/fetch-blob/from.js new file mode 100644 index 0000000..9eaf8bf --- /dev/null +++ b/node_modules/fetch-blob/from.js @@ -0,0 +1,100 @@ +import { statSync, createReadStream, promises as fs } from 'node:fs' +import { basename } from 'node:path' +import DOMException from 'node-domexception' + +import File from './file.js' +import Blob from './index.js' + +const { stat } = fs + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const blobFromSync = (path, type) => fromBlob(statSync(path), path, type) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + * @returns {Promise} + */ +const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type)) + +/** + * @param {string} path filepath on the disk + * @param {string} [type] mimetype to use + */ +const fileFromSync = (path, type) => fromFile(statSync(path), path, type) + +// @ts-ignore +const fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], { type }) + +// @ts-ignore +const fromFile = (stat, path, type = '') => new File([new BlobDataItem({ + path, + size: stat.size, + lastModified: stat.mtimeMs, + start: 0 +})], basename(path), { type, lastModified: stat.mtimeMs }) + +/** + * This is a blob backed up by a file on the disk + * with minium requirement. Its wrapped around a Blob as a blobPart + * so you have no direct access to this. + * + * @private + */ +class BlobDataItem { + #path + #start + + constructor (options) { + this.#path = options.path + this.#start = options.start + this.size = options.size + this.lastModified = options.lastModified + } + + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice (start, end) { + return new BlobDataItem({ + path: this.#path, + lastModified: this.lastModified, + size: end - start, + start: this.#start + start + }) + } + + async * stream () { + const { mtimeMs } = await stat(this.#path) + if (mtimeMs > this.lastModified) { + throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError') + } + yield * createReadStream(this.#path, { + start: this.#start, + end: this.#start + this.size - 1 + }) + } + + get [Symbol.toStringTag] () { + return 'Blob' + } +} + +export default blobFromSync +export { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync } diff --git a/node_modules/fetch-blob/index.d.ts b/node_modules/fetch-blob/index.d.ts new file mode 100644 index 0000000..7a68957 --- /dev/null +++ b/node_modules/fetch-blob/index.d.ts @@ -0,0 +1,3 @@ +/** @type {typeof globalThis.Blob} */ +export const Blob: typeof globalThis.Blob; +export default Blob; diff --git a/node_modules/fetch-blob/index.js b/node_modules/fetch-blob/index.js new file mode 100644 index 0000000..2542ac2 --- /dev/null +++ b/node_modules/fetch-blob/index.js @@ -0,0 +1,250 @@ +/*! fetch-blob. MIT License. Jimmy Wärting */ + +// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x) +// Node has recently added whatwg stream into core + +import './streams.cjs' + +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +/** @param {(Blob | Uint8Array)[]} parts */ +async function * toIterator (parts, clone = true) { + for (const part of parts) { + if ('stream' in part) { + yield * (/** @type {AsyncIterableIterator} */ (part.stream())) + } else if (ArrayBuffer.isView(part)) { + if (clone) { + let position = part.byteOffset + const end = part.byteOffset + part.byteLength + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE) + const chunk = part.buffer.slice(position, position + size) + position += chunk.byteLength + yield new Uint8Array(chunk) + } + } else { + yield part + } + /* c8 ignore next 10 */ + } else { + // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob) + let position = 0, b = (/** @type {Blob} */ (part)) + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + yield new Uint8Array(buffer) + } + } + } +} + +const _Blob = class Blob { + /** @type {Array.<(Blob|Uint8Array)>} */ + #parts = [] + #type = '' + #size = 0 + #endings = 'transparent' + + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor (blobParts = [], options = {}) { + if (typeof blobParts !== 'object' || blobParts === null) { + throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.') + } + + if (typeof blobParts[Symbol.iterator] !== 'function') { + throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.') + } + + if (typeof options !== 'object' && typeof options !== 'function') { + throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.') + } + + if (options === null) options = {} + + const encoder = new TextEncoder() + for (const element of blobParts) { + let part + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)) + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)) + } else if (element instanceof Blob) { + part = element + } else { + part = encoder.encode(`${element}`) + } + + this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size + this.#parts.push(part) + } + + this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}` + const type = options.type === undefined ? '' : String(options.type) + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '' + } + + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size () { + return this.#size + } + + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type () { + return this.#type + } + + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text () { + // More optimized than using this.arrayBuffer() + // that requires twice as much ram + const decoder = new TextDecoder() + let str = '' + for await (const part of toIterator(this.#parts, false)) { + str += decoder.decode(part, { stream: true }) + } + // Remaining + str += decoder.decode() + return str + } + + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer () { + // Easier way... Just a unnecessary overhead + // const view = new Uint8Array(this.size); + // await this.stream().getReader({mode: 'byob'}).read(view); + // return view.buffer; + + const data = new Uint8Array(this.size) + let offset = 0 + for await (const chunk of toIterator(this.#parts, false)) { + data.set(chunk, offset) + offset += chunk.length + } + + return data.buffer + } + + stream () { + const it = toIterator(this.#parts, true) + + return new globalThis.ReadableStream({ + // @ts-ignore + type: 'bytes', + async pull (ctrl) { + const chunk = await it.next() + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value) + }, + + async cancel () { + await it.return() + } + }) + } + + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice (start = 0, end = this.size, type = '') { + const { size } = this + + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size) + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size) + + const span = Math.max(relativeEnd - relativeStart, 0) + const parts = this.#parts + const blobParts = [] + let added = 0 + + for (const part of parts) { + // don't add the overflow to new blobParts + if (added >= span) { + break + } + + const size = ArrayBuffer.isView(part) ? part.byteLength : part.size + if (relativeStart && size <= relativeStart) { + // Skip the beginning and change the relative + // start & end position as we skip the unwanted parts + relativeStart -= size + relativeEnd -= size + } else { + let chunk + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size, relativeEnd)) + added += chunk.byteLength + } else { + chunk = part.slice(relativeStart, Math.min(size, relativeEnd)) + added += chunk.size + } + relativeEnd -= size + blobParts.push(chunk) + relativeStart = 0 // All next sequential parts should start at 0 + } + } + + const blob = new Blob([], { type: String(type).toLowerCase() }) + blob.#size = span + blob.#parts = blobParts + + return blob + } + + get [Symbol.toStringTag] () { + return 'Blob' + } + + static [Symbol.hasInstance] (object) { + return ( + object && + typeof object === 'object' && + typeof object.constructor === 'function' && + ( + typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function' + ) && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) + } +} + +Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}) + +/** @type {typeof globalThis.Blob} */ +export const Blob = _Blob +export default Blob diff --git a/node_modules/fetch-blob/package.json b/node_modules/fetch-blob/package.json new file mode 100644 index 0000000..9d07f39 --- /dev/null +++ b/node_modules/fetch-blob/package.json @@ -0,0 +1,56 @@ +{ + "name": "fetch-blob", + "version": "3.2.0", + "description": "Blob & File implementation in Node.js, originally from node-fetch.", + "main": "index.js", + "type": "module", + "files": [ + "from.js", + "file.js", + "file.d.ts", + "index.js", + "index.d.ts", + "from.d.ts", + "streams.cjs" + ], + "scripts": { + "test": "node --experimental-loader ./test/http-loader.js ./test/test-wpt-in-node.js", + "report": "c8 --reporter json --reporter text npm run test", + "coverage": "npm run report && codecov -f coverage/coverage-final.json", + "prepublishOnly": "tsc --declaration --emitDeclarationOnly --allowJs index.js from.js" + }, + "repository": "https://github.com/node-fetch/fetch-blob.git", + "keywords": [ + "blob", + "file", + "node-fetch" + ], + "engines": { + "node": "^12.20 || >= 14.13" + }, + "author": "Jimmy Wärting (https://jimmy.warting.se)", + "license": "MIT", + "bugs": { + "url": "https://github.com/node-fetch/fetch-blob/issues" + }, + "homepage": "https://github.com/node-fetch/fetch-blob#readme", + "devDependencies": { + "@types/node": "^17.0.9", + "c8": "^7.11.0", + "typescript": "^4.5.4" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + } +} diff --git a/node_modules/fetch-blob/streams.cjs b/node_modules/fetch-blob/streams.cjs new file mode 100644 index 0000000..f760959 --- /dev/null +++ b/node_modules/fetch-blob/streams.cjs @@ -0,0 +1,51 @@ +/* c8 ignore start */ +// 64 KiB (same size chrome slice theirs blob into Uint8array's) +const POOL_SIZE = 65536 + +if (!globalThis.ReadableStream) { + // `node:stream/web` got introduced in v16.5.0 as experimental + // and it's preferred over the polyfilled version. So we also + // suppress the warning that gets emitted by NodeJS for using it. + try { + const process = require('node:process') + const { emitWarning } = process + try { + process.emitWarning = () => {} + Object.assign(globalThis, require('node:stream/web')) + process.emitWarning = emitWarning + } catch (error) { + process.emitWarning = emitWarning + throw error + } + } catch (error) { + // fallback to polyfill implementation + Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js')) + } +} + +try { + // Don't use node: prefix for this, require+node: is not supported until node v14.14 + // Only `import()` can use prefix in 12.20 and later + const { Blob } = require('buffer') + if (Blob && !Blob.prototype.stream) { + Blob.prototype.stream = function name (params) { + let position = 0 + const blob = this + + return new ReadableStream({ + type: 'bytes', + async pull (ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)) + const buffer = await chunk.arrayBuffer() + position += buffer.byteLength + ctrl.enqueue(new Uint8Array(buffer)) + + if (position === blob.size) { + ctrl.close() + } + } + }) + } + } +} catch (error) {} +/* c8 ignore end */ diff --git a/node_modules/formdata-polyfill/FormData.js b/node_modules/formdata-polyfill/FormData.js new file mode 100644 index 0000000..8e73660 --- /dev/null +++ b/node_modules/formdata-polyfill/FormData.js @@ -0,0 +1,441 @@ +/* formdata-polyfill. MIT License. Jimmy Wärting */ + +/* global FormData self Blob File */ +/* eslint-disable no-inner-declarations */ + +if (typeof Blob !== 'undefined' && (typeof FormData === 'undefined' || !FormData.prototype.keys)) { + const global = typeof globalThis === 'object' + ? globalThis + : typeof window === 'object' + ? window + : typeof self === 'object' ? self : this + + // keep a reference to native implementation + const _FormData = global.FormData + + // To be monkey patched + const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send + const _fetch = global.Request && global.fetch + const _sendBeacon = global.navigator && global.navigator.sendBeacon + // Might be a worker thread... + const _match = global.Element && global.Element.prototype + + // Unable to patch Request/Response constructor correctly #109 + // only way is to use ES6 class extend + // https://github.com/babel/babel/issues/1966 + + const stringTag = global.Symbol && Symbol.toStringTag + + // Add missing stringTags to blob and files + if (stringTag) { + if (!Blob.prototype[stringTag]) { + Blob.prototype[stringTag] = 'Blob' + } + + if ('File' in global && !File.prototype[stringTag]) { + File.prototype[stringTag] = 'File' + } + } + + // Fix so you can construct your own File + try { + new File([], '') // eslint-disable-line + } catch (a) { + global.File = function File (b, d, c) { + const blob = new Blob(b, c || {}) + const t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date() + + Object.defineProperties(blob, { + name: { + value: d + }, + lastModified: { + value: +t + }, + toString: { + value () { + return '[object File]' + } + } + }) + + if (stringTag) { + Object.defineProperty(blob, stringTag, { + value: 'File' + }) + } + + return blob + } + } + + function ensureArgs (args, expected) { + if (args.length < expected) { + throw new TypeError(`${expected} argument required, but only ${args.length} present.`) + } + } + + /** + * @param {string} name + * @param {string | undefined} filename + * @returns {[string, File|string]} + */ + function normalizeArgs (name, value, filename) { + if (value instanceof Blob) { + filename = filename !== undefined + ? String(filename + '') + : typeof value.name === 'string' + ? value.name + : 'blob' + + if (value.name !== filename || Object.prototype.toString.call(value) === '[object Blob]') { + value = new File([value], filename) + } + return [String(name), value] + } + return [String(name), String(value)] + } + + // normalize line feeds for textarea + // https://html.spec.whatwg.org/multipage/form-elements.html#textarea-line-break-normalisation-transformation + function normalizeLinefeeds (value) { + return value.replace(/\r?\n|\r/g, '\r\n') + } + + /** + * @template T + * @param {ArrayLike} arr + * @param {{ (elm: T): void; }} cb + */ + function each (arr, cb) { + for (let i = 0; i < arr.length; i++) { + cb(arr[i]) + } + } + + const escape = str => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + + /** + * @implements {Iterable} + */ + class FormDataPolyfill { + /** + * FormData class + * + * @param {HTMLFormElement=} form + */ + constructor (form) { + /** @type {[string, string|File][]} */ + this._data = [] + + const self = this + form && each(form.elements, (/** @type {HTMLInputElement} */ elm) => { + if ( + !elm.name || + elm.disabled || + elm.type === 'submit' || + elm.type === 'button' || + elm.matches('form fieldset[disabled] *') + ) return + + if (elm.type === 'file') { + const files = elm.files && elm.files.length + ? elm.files + : [new File([], '', { type: 'application/octet-stream' })] // #78 + + each(files, file => { + self.append(elm.name, file) + }) + } else if (elm.type === 'select-multiple' || elm.type === 'select-one') { + each(elm.options, opt => { + !opt.disabled && opt.selected && self.append(elm.name, opt.value) + }) + } else if (elm.type === 'checkbox' || elm.type === 'radio') { + if (elm.checked) self.append(elm.name, elm.value) + } else { + const value = elm.type === 'textarea' ? normalizeLinefeeds(elm.value) : elm.value + self.append(elm.name, value) + } + }) + } + + /** + * Append a field + * + * @param {string} name field name + * @param {string|Blob|File} value string / blob / file + * @param {string=} filename filename to use with blob + * @return {undefined} + */ + append (name, value, filename) { + ensureArgs(arguments, 2) + this._data.push(normalizeArgs(name, value, filename)) + } + + /** + * Delete all fields values given name + * + * @param {string} name Field name + * @return {undefined} + */ + delete (name) { + ensureArgs(arguments, 1) + const result = [] + name = String(name) + + each(this._data, entry => { + entry[0] !== name && result.push(entry) + }) + + this._data = result + } + + /** + * Iterate over all fields as [name, value] + * + * @return {Iterator} + */ + * entries () { + for (var i = 0; i < this._data.length; i++) { + yield this._data[i] + } + } + + /** + * Iterate over all fields + * + * @param {Function} callback Executed for each item with parameters (value, name, thisArg) + * @param {Object=} thisArg `this` context for callback function + */ + forEach (callback, thisArg) { + ensureArgs(arguments, 1) + for (const [name, value] of this) { + callback.call(thisArg, value, name, this) + } + } + + /** + * Return first field value given name + * or null if non existent + * + * @param {string} name Field name + * @return {string|File|null} value Fields value + */ + get (name) { + ensureArgs(arguments, 1) + const entries = this._data + name = String(name) + for (let i = 0; i < entries.length; i++) { + if (entries[i][0] === name) { + return entries[i][1] + } + } + return null + } + + /** + * Return all fields values given name + * + * @param {string} name Fields name + * @return {Array} [{String|File}] + */ + getAll (name) { + ensureArgs(arguments, 1) + const result = [] + name = String(name) + each(this._data, data => { + data[0] === name && result.push(data[1]) + }) + + return result + } + + /** + * Check for field name existence + * + * @param {string} name Field name + * @return {boolean} + */ + has (name) { + ensureArgs(arguments, 1) + name = String(name) + for (let i = 0; i < this._data.length; i++) { + if (this._data[i][0] === name) { + return true + } + } + return false + } + + /** + * Iterate over all fields name + * + * @return {Iterator} + */ + * keys () { + for (const [name] of this) { + yield name + } + } + + /** + * Overwrite all values given name + * + * @param {string} name Filed name + * @param {string} value Field value + * @param {string=} filename Filename (optional) + */ + set (name, value, filename) { + ensureArgs(arguments, 2) + name = String(name) + /** @type {[string, string|File][]} */ + const result = [] + const args = normalizeArgs(name, value, filename) + let replace = true + + // - replace the first occurrence with same name + // - discards the remaining with same name + // - while keeping the same order items where added + each(this._data, data => { + data[0] === name + ? replace && (replace = !result.push(args)) + : result.push(data) + }) + + replace && result.push(args) + + this._data = result + } + + /** + * Iterate over all fields + * + * @return {Iterator} + */ + * values () { + for (const [, value] of this) { + yield value + } + } + + /** + * Return a native (perhaps degraded) FormData with only a `append` method + * Can throw if it's not supported + * + * @return {FormData} + */ + ['_asNative'] () { + const fd = new _FormData() + + for (const [name, value] of this) { + fd.append(name, value) + } + + return fd + } + + /** + * [_blob description] + * + * @return {Blob} [description] + */ + ['_blob'] () { + const boundary = '----formdata-polyfill-' + Math.random(), + chunks = [], + p = `--${boundary}\r\nContent-Disposition: form-data; name="` + this.forEach((value, name) => typeof value == 'string' + ? chunks.push(p + escape(normalizeLinefeeds(name)) + `"\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + : chunks.push(p + escape(normalizeLinefeeds(name)) + `"; filename="${escape(value.name)}"\r\nContent-Type: ${value.type||"application/octet-stream"}\r\n\r\n`, value, `\r\n`)) + chunks.push(`--${boundary}--`) + return new Blob(chunks, { + type: "multipart/form-data; boundary=" + boundary + }) + } + + /** + * The class itself is iterable + * alias for formdata.entries() + * + * @return {Iterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Create the default string description. + * + * @return {string} [object FormData] + */ + toString () { + return '[object FormData]' + } + } + + if (_match && !_match.matches) { + _match.matches = + _match.matchesSelector || + _match.mozMatchesSelector || + _match.msMatchesSelector || + _match.oMatchesSelector || + _match.webkitMatchesSelector || + function (s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s) + var i = matches.length + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1 + } + } + + if (stringTag) { + /** + * Create the default string description. + * It is accessed internally by the Object.prototype.toString(). + */ + FormDataPolyfill.prototype[stringTag] = 'FormData' + } + + // Patch xhr's send method to call _blob transparently + if (_send) { + const setRequestHeader = global.XMLHttpRequest.prototype.setRequestHeader + + global.XMLHttpRequest.prototype.setRequestHeader = function (name, value) { + setRequestHeader.call(this, name, value) + if (name.toLowerCase() === 'content-type') this._hasContentType = true + } + + global.XMLHttpRequest.prototype.send = function (data) { + // need to patch send b/c old IE don't send blob's type (#44) + if (data instanceof FormDataPolyfill) { + const blob = data['_blob']() + if (!this._hasContentType) this.setRequestHeader('Content-Type', blob.type) + _send.call(this, blob) + } else { + _send.call(this, data) + } + } + } + + // Patch fetch's function to call _blob transparently + if (_fetch) { + global.fetch = function (input, init) { + if (init && init.body && init.body instanceof FormDataPolyfill) { + init.body = init.body['_blob']() + } + + return _fetch.call(this, input, init) + } + } + + // Patch navigator.sendBeacon to use native FormData + if (_sendBeacon) { + global.navigator.sendBeacon = function (url, data) { + if (data instanceof FormDataPolyfill) { + data = data['_asNative']() + } + return _sendBeacon.call(this, url, data) + } + } + + global['FormData'] = FormDataPolyfill +} diff --git a/node_modules/formdata-polyfill/LICENSE b/node_modules/formdata-polyfill/LICENSE new file mode 100644 index 0000000..fd0f555 --- /dev/null +++ b/node_modules/formdata-polyfill/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jimmy Karl Roland Wärting + +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/node_modules/formdata-polyfill/README.md b/node_modules/formdata-polyfill/README.md new file mode 100644 index 0000000..8355299 --- /dev/null +++ b/node_modules/formdata-polyfill/README.md @@ -0,0 +1,145 @@ +### A `FormData` polyfill for the browser ...and a module for NodeJS (`New!`) + +```bash +npm install formdata-polyfill +``` + +The browser polyfill will likely have done its part already, and i hope you stop supporting old browsers c",)
+But NodeJS still laks a proper FormData
The good old form-data package is a very old and isn't spec compatible and dose some abnormal stuff to construct and read FormData instances that other http libraries are not happy about when it comes to follow the spec. + +### The NodeJS / ESM version +- The modular (~2.3 KiB minified uncompressed) version of this package is independent of any browser stuff and don't patch anything +- It's as pure/spec compatible as it possible gets the test are run by WPT. +- It's compatible with [node-fetch](https://github.com/node-fetch/node-fetch). +- It have higher platform dependencies as it uses classes, symbols, ESM & private fields +- Only dependency it has is [fetch-blob](https://github.com/node-fetch/fetch-blob) + +```js +// Node example +import fetch from 'node-fetch' +import File from 'fetch-blob/file.js' +import { fileFromSync } from 'fetch-blob/from.js' +import { FormData } from 'formdata-polyfill/esm.min.js' + +const file = fileFromSync('./README.md') +const fd = new FormData() + +fd.append('file-upload', new File(['abc'], 'hello-world.txt')) +fd.append('file-upload', file) + +// it's also possible to append file/blob look-a-like items +// if you have streams coming from other destinations +fd.append('file-upload', { + size: 123, + type: '', + name: 'cat-video.mp4', + stream() { return stream }, + [Symbol.toStringTag]: 'File' +}) + +fetch('https://httpbin.org/post', { method: 'POST', body: fd }) +``` + +---- + +It also comes with way to convert FormData into Blobs - it's not something that every developer should have to deal with. +It's mainly for [node-fetch](https://github.com/node-fetch/node-fetch) and other http library to ease the process of serializing a FormData into a blob and just wish to deal with Blobs instead (Both Deno and Undici adapted a version of this [formDataToBlob](https://github.com/jimmywarting/FormData/blob/5ddea9e0de2fc5e246ab1b2f9d404dee0c319c02/formdata-to-blob.js) to the core and passes all WPT tests run by the browser itself) +```js +import { Readable } from 'node:stream' +import { FormData, formDataToBlob } from 'formdata-polyfill/esm.min.js' + +const blob = formDataToBlob(new FormData()) +fetch('https://httpbin.org/post', { method: 'POST', body: blob }) + +// node built in http and other similar http library have to do: +const stream = Readable.from(blob.stream()) +const req = http.request('http://httpbin.org/post', { + method: 'post', + headers: { + 'Content-Length': blob.size, + 'Content-Type': blob.type + } +}) +stream.pipe(req) +``` + +PS: blob & file that are appended to the FormData will not be read until any of the serialized blob read-methods gets called +...so uploading very large files is no biggie + +### Browser polyfill + +usage: + +```js +import 'formdata-polyfill' // that's it +``` + +The browser polyfill conditionally replaces the native implementation rather than fixing the missing functions, +since otherwise there is no way to get or delete existing values in the FormData object. +Therefore this also patches `XMLHttpRequest.prototype.send` and `fetch` to send the `FormData` as a blob, +and `navigator.sendBeacon` to send native `FormData`. + +I was unable to patch the Response/Request constructor +so if you are constructing them with FormData then you need to call `fd._blob()` manually. + +```js +new Request(url, { + method: 'post', + body: fd._blob ? fd._blob() : fd +}) +``` + +Dependencies +--- + +If you need to support IE <= 9 then I recommend you to include eligrey's [blob.js] +(which i hope you don't - since IE is now dead) + +
+ Updating from 2.x to 3.x + +Previously you had to import the polyfill and use that, +since it didn't replace the global (existing) FormData implementation. +But now it transparently calls `_blob()` for you when you are sending something with fetch or XHR, +by way of monkey-patching the `XMLHttpRequest.prototype.send` and `fetch` functions. + +So you maybe had something like this: + +```javascript +var FormData = require('formdata-polyfill') +var fd = new FormData(form) +xhr.send(fd._blob()) +``` + +There is no longer anything exported from the module +(though you of course still need to import it to install the polyfill), +so you can now use the FormData object as normal: + +```javascript +require('formdata-polyfill') +var fd = new FormData(form) +xhr.send(fd) +``` + +
+ + + +Native Browser compatibility (as of 2021-05-08) +--- +Based on this you can decide for yourself if you need this polyfill. + +[![screenshot](https://user-images.githubusercontent.com/1148376/117550329-0993aa80-b040-11eb-976c-14e31f1a3ba4.png)](https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility) + + + +This normalizes support for the FormData API: + + - `append` with filename + - `delete()`, `get()`, `getAll()`, `has()`, `set()` + - `entries()`, `keys()`, `values()`, and support for `for...of` + - Available in web workers (just include the polyfill) + + [npm-image]: https://img.shields.io/npm/v/formdata-polyfill.svg + [npm-url]: https://www.npmjs.com/package/formdata-polyfill + [blob.js]: https://github.com/eligrey/Blob.js diff --git a/node_modules/formdata-polyfill/esm.min.d.ts b/node_modules/formdata-polyfill/esm.min.d.ts new file mode 100644 index 0000000..b45f42e --- /dev/null +++ b/node_modules/formdata-polyfill/esm.min.d.ts @@ -0,0 +1,5 @@ +export declare const FormData: { + new (): FormData; + prototype: FormData; +}; +export declare function formDataToBlob(formData: FormData): Blob; diff --git a/node_modules/formdata-polyfill/esm.min.js b/node_modules/formdata-polyfill/esm.min.js new file mode 100644 index 0000000..745ca29 --- /dev/null +++ b/node_modules/formdata-polyfill/esm.min.js @@ -0,0 +1,40 @@ +/*! formdata-polyfill. MIT License. Jimmy Wärting */ + +import C from 'fetch-blob' +import F from 'fetch-blob/file.js' + +var {toStringTag:t,iterator:i,hasInstance:h}=Symbol, +r=Math.random, +m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), +f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']), +e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), +x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} +append(...a){x('append',arguments,2);this.#d.push(f(...a))} +delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)} +get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b} +has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} +forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)} +set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b} +*entries(){yield*this.#d} +*keys(){for(var[a]of this)yield a} +*values(){for(var[,a]of this)yield a}} + +/** @param {FormData} F */ +export function formDataToBlob (F,B=C){ +var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="` +F.forEach((v,n)=>typeof v=='string' +?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? */ + +const escape = (str, filename) => + (filename ? str : str.replace(/\r?\n|\r/g, '\r\n')) + .replace(/\n/g, '%0A') + .replace(/\r/g, '%0D') + .replace(/"/g, '%22') + +/** + * pure function to convert any formData instance to a Blob + * instances synchronous without reading all of the files + * + * @param {FormData|*} formData an instance of a formData Class + * @param {Blob|*} [BlobClass=Blob] the Blob class to use when constructing it + */ +export function formDataToBlob (formData, BlobClass = Blob) { + const boundary = ('----formdata-polyfill-' + Math.random()) + const chunks = [] + const prefix = `--${boundary}\r\nContent-Disposition: form-data; name="` + + for (let [name, value] of formData) { + if (typeof value === 'string') { + chunks.push(prefix + escape(name) + `"\r\n\r\n${value.replace(/\r(?!\n)|(? */ +;(function(){var h;function l(a){var b=0;return function(){return b>>0)+"_",e=0;return b}); +r("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c=12.20.0" + }, + "keywords": [ + "formdata", + "fetch", + "node-fetch", + "html5", + "browser", + "polyfill" + ], + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/FormData/issues" + }, + "homepage": "https://github.com/jimmywarting/FormData#readme", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "devDependencies": { + "@types/google-closure-compiler": "^0.0.19", + "@types/node": "^16.7.10", + "google-closure-compiler": "^20210808.0.0" + } +} diff --git a/node_modules/heap/.npmignore b/node_modules/heap/.npmignore new file mode 100644 index 0000000..ef5f69b --- /dev/null +++ b/node_modules/heap/.npmignore @@ -0,0 +1,2 @@ +*.swp +node_modules/ diff --git a/node_modules/heap/.travis.yml b/node_modules/heap/.travis.yml new file mode 100644 index 0000000..18ae2d8 --- /dev/null +++ b/node_modules/heap/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.11" + - "0.10" diff --git a/node_modules/heap/Makefile b/node_modules/heap/Makefile new file mode 100644 index 0000000..5030dee --- /dev/null +++ b/node_modules/heap/Makefile @@ -0,0 +1,17 @@ +TEST_TIMEOUT = 2000 +TEST_REPORTER = spec + +lib/heap.js: src/heap.coffee + @coffee -c -o lib src + +test: + @NODE_ENV=test \ + node_modules/.bin/mocha \ + --require should \ + --timeout $(TEST_TIMEOUT) \ + --reporter $(TEST_REPORTER) \ + --compilers coffee:coffee-script \ + test/*.coffee + + +.PHONY: test diff --git a/node_modules/heap/README.md b/node_modules/heap/README.md new file mode 100644 index 0000000..8e07e16 --- /dev/null +++ b/node_modules/heap/README.md @@ -0,0 +1,211 @@ +Heap.js +======= + +[![Build Status](https://travis-ci.org/qiao/heap.js.svg?branch=master)](https://travis-ci.org/qiao/heap.js) + +A binary heap implementation in CoffeeScript/JavaScript. Ported from Python's [heapq](http://docs.python.org/library/heapq.html) module. + + +Download +-------- + +This module can be used in either the browser or node.js. + +for browser use, you may [download the script](https://raw.github.com/qiao/heap.js/master/lib/heap.js) and include it in you web page. + +```html + +``` + +for node.js, you may install it via npm: + +```bash +npm install heap +``` + +then require it: + +``` +var Heap = require('heap'); +``` + +Examples +------- + + +push and pop + +```js +var heap = new Heap(); +heap.push(3); +heap.push(1); +heap.push(2); +heap.pop(); // 1 +``` + +custom comparison function + +```js +var heap = new Heap(function(a, b) { + return a.foo - b.foo; +}); +heap.push({foo: 3}); +heap.push({foo: 1}); +heap.push({foo: 2}); +heap.pop(); // {foo: 1} +``` + +find 3 largest/smallest items in an array + +```js +var array = [1, 3, 4, 2, 5]; +Heap.nlargest(array, 3); // [5, 4, 3] +Heap.nsmallest(array, 3); // [1, 2, 3] +``` + +Document +-------- + +This module exposes only one object, namely the Heap class. + +### Constructor: Heap([cmp]) ### + +The constructor receives a comparison function as an optional parameter. If omitted, the heap is built as a min-heap, which means that the smallest element will be popped out first. + +If the comparison function is supplied, the heap will be built according to the +return value of the comparison function. + +* if cmp(a, b) < 0, then item a will come prior to b +* if cmp(a, b) > 0, then item b will come prior to a + +So, the comparison function has the following form: + +```js +function cmp(a, b) { + if (a is prior to b) { + return -1; + } + if (b is prior to a) { + return 1; + } + return 0; +} +``` + +To compare numbers, simply: + +```js +function cmp(a, b) { + return a - b; +} +``` + +### Instance Methods ### + +**push(item)** (alias: **insert**) + +Push item onto heap. + +**pop()** + +Pop the smallest item off the heap and return it. + +**peek()** (alias: **top** / **front**) + +Return the smallest item of the heap. + +**replace(item)** + +Pop and return the current smallest value, and add the new item. + +This is more efficient than pop() followed by push(), and can be +more appropriate when using a fixed size heap. Note that the value +returned may be larger than item! + +**pushpop(item)** + +Fast version of a push followed by a pop. + +**heapify()** + +Rebuild the heap. This method may come handy when the priority of the +internal data is being modified. + +**updateItem(item)** + +Update the position of the given item in the heap. +This function should be called every time the item is being modified. + +**empty()** + +Determine whether the heap is empty. + +**size()** + +Get the number of elements stored in the heap. + +**toArray()** + +Return the array representation of the heap. (note: the array is a shallow copy of the heap's internal nodes) + +**clone()** (alias: **copy**) + +Return a clone of the heap. (note: the internal data is a shallow copy of the original one) + +### Static Methods ### + +NOTE: All the static methods are designed to be applied on arrays. + +**push(array, item, [cmp])** + +Push item onto array, maintaining the heap invariant. + +**pop(array, [cmp])** + +Pop the smallest item off the array, maintaining the heap invariant. + +**replace(array, item, [cmp])** + +Pop and return the current smallest value, and add the new item. + +This is more efficient than heappop() followed by heappush(), and can be +more appropriate when using a fixed size heap. Note that the value +returned may be larger than item! + +**pushpop(array, item, [cmp])** + +Fast version of a heappush followed by a heappop. + +**heapify(array, [cmp])** + +Build the heap. + +**updateItem(array, item, [cmp])** + +Update the position of the given item in the heap. +This function should be called every time the item is being modified. + +**nlargest(array, n, [cmp])** + +Find the n largest elements in a dataset. + +**nsmallest(array, n, [cmp])** + +Find the n smallest elements in a dataset. + + +License +------- + +Ported by Xueqiao Xu <xueqiaoxu@gmail.com> + +PSF LICENSE AGREEMENT FOR PYTHON 2.7.2 + +1. This LICENSE AGREEMENT is between the Python Software Foundation (“PSF”), and the Individual or Organization (“Licensee”) accessing and otherwise using Python 2.7.2 software in source or binary form and its associated documentation. +2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 2.7.2 alone or in any derivative version, provided, however, that PSF’s License Agreement and PSF’s notice of copyright, i.e., “Copyright © 2001-2012 Python Software Foundation; All Rights Reserved” are retained in Python 2.7.2 alone or in any derivative version prepared by Licensee. +3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.7.2 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 2.7.2. +4. PSF is making Python 2.7.2 available to Licensee on an “AS IS” basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.7.2 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.7.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.7.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. +6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. +7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. +8. By copying, installing or otherwise using Python 2.7.2, Licensee agrees to be bound by the terms and conditions of this License Agreement. diff --git a/node_modules/heap/bower.json b/node_modules/heap/bower.json new file mode 100644 index 0000000..010e876 --- /dev/null +++ b/node_modules/heap/bower.json @@ -0,0 +1,19 @@ +{ + "name" : "heap" + , "version" : "0.2.5" + , "description" : "binary heap (priority queue) algorithms (ported from Python's heapq module)" + , "homepage" : "https://github.com/qiao/heap.js" + , "keywords" : ["algorithm", "data structure", "heap"] + , "author" : "Xueqiao Xu " + , "main" : "lib/heap.js" + , "dependencies" : {} + , "devDependencies" : {} + , "repository" : { + "type" : "git" + , "url" : "git://github.com/qiao/heap.js.git" + } + , "licenses" : [{ + "type" : "PSF" + , "url" : "http://docs.python.org/license.html" + }] +} diff --git a/node_modules/heap/index.js b/node_modules/heap/index.js new file mode 100644 index 0000000..f4c5e90 --- /dev/null +++ b/node_modules/heap/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/heap'); diff --git a/node_modules/heap/lib/heap.js b/node_modules/heap/lib/heap.js new file mode 100644 index 0000000..d3dcb74 --- /dev/null +++ b/node_modules/heap/lib/heap.js @@ -0,0 +1,369 @@ +// Generated by CoffeeScript 1.8.0 +(function() { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; + + floor = Math.floor, min = Math.min; + + + /* + Default comparison function to be used + */ + + defaultCmp = function(x, y) { + if (x < y) { + return -1; + } + if (x > y) { + return 1; + } + return 0; + }; + + + /* + Insert item x in list a, and keep it sorted assuming a is sorted. + + If x is already in a, insert it to the right of the rightmost x. + + Optional args lo (default 0) and hi (default a.length) bound the slice + of a to be searched. + */ + + insort = function(a, x, lo, hi, cmp) { + var mid; + if (lo == null) { + lo = 0; + } + if (cmp == null) { + cmp = defaultCmp; + } + if (lo < 0) { + throw new Error('lo must be non-negative'); + } + if (hi == null) { + hi = a.length; + } + while (lo < hi) { + mid = floor((lo + hi) / 2); + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); + }; + + + /* + Push item onto heap, maintaining the heap invariant. + */ + + heappush = function(array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; + } + array.push(item); + return _siftdown(array, 0, array.length - 1, cmp); + }; + + + /* + Pop the smallest item off the heap, maintaining the heap invariant. + */ + + heappop = function(array, cmp) { + var lastelt, returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + lastelt = array.pop(); + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; + } + return returnitem; + }; + + + /* + Pop and return the current smallest value, and add the new item. + + This is more efficient than heappop() followed by heappush(), and can be + more appropriate when using a fixed size heap. Note that the value + returned may be larger than item! That constrains reasonable use of + this routine unless written as part of a conditional replacement: + if item > array[0] + item = heapreplace(array, item) + */ + + heapreplace = function(array, item, cmp) { + var returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + returnitem = array[0]; + array[0] = item; + _siftup(array, 0, cmp); + return returnitem; + }; + + + /* + Fast version of a heappush followed by a heappop. + */ + + heappushpop = function(array, item, cmp) { + var _ref; + if (cmp == null) { + cmp = defaultCmp; + } + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + _siftup(array, 0, cmp); + } + return item; + }; + + + /* + Transform list into a heap, in-place, in O(array.length) time. + */ + + heapify = function(array, cmp) { + var i, _i, _j, _len, _ref, _ref1, _results, _results1; + if (cmp == null) { + cmp = defaultCmp; + } + _ref1 = (function() { + _results1 = []; + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } + return _results1; + }).apply(this).reverse(); + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; + _results.push(_siftup(array, i, cmp)); + } + return _results; + }; + + + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ + + updateItem = function(array, item, cmp) { + var pos; + if (cmp == null) { + cmp = defaultCmp; + } + pos = array.indexOf(item); + if (pos === -1) { + return; + } + _siftdown(array, 0, pos, cmp); + return _siftup(array, pos, cmp); + }; + + + /* + Find the n largest elements in a dataset. + */ + + nlargest = function(array, n, cmp) { + var elem, result, _i, _len, _ref; + if (cmp == null) { + cmp = defaultCmp; + } + result = array.slice(0, n); + if (!result.length) { + return result; + } + heapify(result, cmp); + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } + return result.sort(cmp).reverse(); + }; + + + /* + Find the n smallest elements in a dataset. + */ + + nsmallest = function(array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; + if (cmp == null) { + cmp = defaultCmp; + } + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); + if (!result.length) { + return result; + } + los = result[result.length - 1]; + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; + } + } + return result; + } + heapify(array, cmp); + _results = []; + for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + _results.push(heappop(array, cmp)); + } + return _results; + }; + + _siftdown = function(array, startpos, pos, cmp) { + var newitem, parent, parentpos; + if (cmp == null) { + cmp = defaultCmp; + } + newitem = array[pos]; + while (pos > startpos) { + parentpos = (pos - 1) >> 1; + parent = array[parentpos]; + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; + } + break; + } + return array[pos] = newitem; + }; + + _siftup = function(array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; + if (cmp == null) { + cmp = defaultCmp; + } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; + while (childpos < endpos) { + rightpos = childpos + 1; + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; + } + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; + } + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; + + Heap = (function() { + Heap.push = heappush; + + Heap.pop = heappop; + + Heap.replace = heapreplace; + + Heap.pushpop = heappushpop; + + Heap.heapify = heapify; + + Heap.updateItem = updateItem; + + Heap.nlargest = nlargest; + + Heap.nsmallest = nsmallest; + + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } + + Heap.prototype.push = function(x) { + return heappush(this.nodes, x, this.cmp); + }; + + Heap.prototype.pop = function() { + return heappop(this.nodes, this.cmp); + }; + + Heap.prototype.peek = function() { + return this.nodes[0]; + }; + + Heap.prototype.contains = function(x) { + return this.nodes.indexOf(x) !== -1; + }; + + Heap.prototype.replace = function(x) { + return heapreplace(this.nodes, x, this.cmp); + }; + + Heap.prototype.pushpop = function(x) { + return heappushpop(this.nodes, x, this.cmp); + }; + + Heap.prototype.heapify = function() { + return heapify(this.nodes, this.cmp); + }; + + Heap.prototype.updateItem = function(x) { + return updateItem(this.nodes, x, this.cmp); + }; + + Heap.prototype.clear = function() { + return this.nodes = []; + }; + + Heap.prototype.empty = function() { + return this.nodes.length === 0; + }; + + Heap.prototype.size = function() { + return this.nodes.length; + }; + + Heap.prototype.clone = function() { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; + + Heap.prototype.toArray = function() { + return this.nodes.slice(0); + }; + + Heap.prototype.insert = Heap.prototype.push; + + Heap.prototype.top = Heap.prototype.peek; + + Heap.prototype.front = Heap.prototype.peek; + + Heap.prototype.has = Heap.prototype.contains; + + Heap.prototype.copy = Heap.prototype.clone; + + return Heap; + + })(); + + if (typeof module !== "undefined" && module !== null ? module.exports : void 0) { + module.exports = Heap; + } else { + window.Heap = Heap; + } + +}).call(this); diff --git a/node_modules/heap/package.json b/node_modules/heap/package.json new file mode 100644 index 0000000..0c799dc --- /dev/null +++ b/node_modules/heap/package.json @@ -0,0 +1,26 @@ +{ + "name" : "heap" + , "version" : "0.2.5" + , "description" : "binary heap (priority queue) algorithms (ported from Python's heapq module)" + , "homepage" : "https://github.com/qiao/heap.js" + , "keywords" : ["algorithm", "data structure", "heap"] + , "author" : "Xueqiao Xu " + , "main" : "./index.js" + , "dependencies" : {} + , "devDependencies" : { + "coffee-script" : "1.3.x" + , "mocha" : "1.0.x" + , "should" : "0.6.x" + } + , "scripts" : { + "test" : "make test" + } + , "repository" : { + "type" : "git" + , "url" : "git://github.com/qiao/heap.js.git" + } + , "licenses" : [{ + "type" : "PSF" + , "url" : "http://docs.python.org/license.html" + }] +} diff --git a/node_modules/heap/src/heap.coffee b/node_modules/heap/src/heap.coffee new file mode 100644 index 0000000..f0753b5 --- /dev/null +++ b/node_modules/heap/src/heap.coffee @@ -0,0 +1,213 @@ +{floor, min} = Math + +### +Default comparison function to be used +### +defaultCmp = (x, y) -> + return -1 if x < y + return 1 if x > y + 0 + +### +Insert item x in list a, and keep it sorted assuming a is sorted. + +If x is already in a, insert it to the right of the rightmost x. + +Optional args lo (default 0) and hi (default a.length) bound the slice +of a to be searched. +### +insort = (a, x, lo=0, hi, cmp=defaultCmp) -> + throw new Error('lo must be non-negative') if lo < 0 + hi ?= a.length + while lo < hi + mid = floor((lo + hi) / 2) + if cmp(x, a[mid]) < 0 + hi = mid + else + lo = mid + 1 + a[lo...lo] = x + +### +Push item onto heap, maintaining the heap invariant. +### +heappush = (array, item, cmp=defaultCmp) -> + array.push(item) + _siftdown(array, 0, array.length - 1, cmp) + +### +Pop the smallest item off the heap, maintaining the heap invariant. +### +heappop = (array, cmp=defaultCmp) -> + lastelt = array.pop() + if array.length + returnitem = array[0] + array[0] = lastelt + _siftup(array, 0, cmp) + else + returnitem = lastelt + returnitem + +### +Pop and return the current smallest value, and add the new item. + +This is more efficient than heappop() followed by heappush(), and can be +more appropriate when using a fixed size heap. Note that the value +returned may be larger than item! That constrains reasonable use of +this routine unless written as part of a conditional replacement: + if item > array[0] + item = heapreplace(array, item) +### +heapreplace = (array, item, cmp=defaultCmp) -> + returnitem = array[0] + array[0] = item + _siftup(array, 0, cmp) + returnitem + +### +Fast version of a heappush followed by a heappop. +### +heappushpop = (array, item, cmp=defaultCmp) -> + if array.length and cmp(array[0], item) < 0 + [item, array[0]] = [array[0], item] + _siftup(array, 0, cmp) + item + +### +Transform list into a heap, in-place, in O(array.length) time. +### +heapify = (array, cmp=defaultCmp) -> + for i in [0...floor(array.length / 2)].reverse() + _siftup(array, i, cmp) + +### +Update the position of the given item in the heap. +This function should be called every time the item is being modified. +### +updateItem = (array, item, cmp=defaultCmp) -> + pos = array.indexOf(item) + return if pos is -1 + _siftdown(array, 0, pos, cmp) + _siftup(array, pos, cmp) + +### +Find the n largest elements in a dataset. +### +nlargest = (array, n, cmp=defaultCmp) -> + result = array[0...n] + return result unless result.length + heapify(result, cmp) + heappushpop(result, elem, cmp) for elem in array[n..] + result.sort(cmp).reverse() + +### +Find the n smallest elements in a dataset. +### +nsmallest = (array, n, cmp=defaultCmp) -> + if n * 10 <= array.length + result = array[0...n].sort(cmp) + return result unless result.length + los = result[result.length - 1] + for elem in array[n..] + if cmp(elem, los) < 0 + insort(result, elem, 0, null, cmp) + result.pop() + los = result[result.length - 1] + return result + + heapify(array, cmp) + (heappop(array, cmp) for i in [0...min(n, array.length)]) + +_siftdown = (array, startpos, pos, cmp=defaultCmp) -> + newitem = array[pos] + while pos > startpos + parentpos = (pos - 1) >> 1 + parent = array[parentpos] + if cmp(newitem, parent) < 0 + array[pos] = parent + pos = parentpos + continue + break + array[pos] = newitem + +_siftup = (array, pos, cmp=defaultCmp) -> + endpos = array.length + startpos = pos + newitem = array[pos] + childpos = 2 * pos + 1 + while childpos < endpos + rightpos = childpos + 1 + if rightpos < endpos and not (cmp(array[childpos], array[rightpos]) < 0) + childpos = rightpos + array[pos] = array[childpos] + pos = childpos + childpos = 2 * pos + 1 + array[pos] = newitem + _siftdown(array, startpos, pos, cmp) + +class Heap + @push: heappush + @pop: heappop + @replace: heapreplace + @pushpop: heappushpop + @heapify: heapify + @updateItem: updateItem + @nlargest: nlargest + @nsmallest: nsmallest + + constructor: (@cmp=defaultCmp) -> + @nodes = [] + + push: (x) -> + heappush(@nodes, x, @cmp) + + pop: -> + heappop(@nodes, @cmp) + + peek: -> + @nodes[0] + + contains: (x) -> + @nodes.indexOf(x) isnt -1 + + replace: (x) -> + heapreplace(@nodes, x, @cmp) + + pushpop: (x) -> + heappushpop(@nodes, x, @cmp) + + heapify: -> + heapify(@nodes, @cmp) + + updateItem: (x) -> + updateItem(@nodes, x, @cmp) + + clear: -> + @nodes = [] + + empty: -> + @nodes.length is 0 + + size: -> + @nodes.length + + clone: -> + heap = new Heap() + heap.nodes = @nodes.slice(0) + heap + + toArray: -> + @nodes.slice(0) + + # aliases + insert: @::push + top: @::peek + front: @::peek + has: @::contains + copy: @::clone + + +# exports to global +if module?.exports + module.exports = Heap +else + window.Heap = Heap diff --git a/node_modules/heap/test/heap.test.coffee b/node_modules/heap/test/heap.test.coffee new file mode 100644 index 0000000..6c1d3f2 --- /dev/null +++ b/node_modules/heap/test/heap.test.coffee @@ -0,0 +1,100 @@ +Heap = require '..' +{random} = Math + +describe 'Heap#push, Heap#pop', -> + it 'should sort an array using push and pop', -> + heap = new Heap + heap.push(random()) for i in [1..10] + sorted = (heap.pop() until heap.empty()) + sorted.slice().sort().should.eql(sorted) + + it 'should work with custom comparison function', -> + cmp = (a, b) -> + return -1 if a > b + return 1 if a < b + 0 + heap = new Heap(cmp) + heap.push(random()) for i in [1..10] + sorted = (heap.pop() until heap.empty()) + sorted.slice().sort().reverse().should.eql(sorted) + +describe 'Heap#replace', -> + it 'should behave like pop() followed by push()', -> + heap = new Heap + heap.push(v) for v in [1..5] + heap.replace(3).should.eql(1) + heap.toArray().sort().should.eql([2,3,3,4,5]) + +describe 'Heap#pushpop', -> + it 'should behave like push() followed by pop()', -> + heap = new Heap + heap.push(v) for v in [1..5] + heap.pushpop(6).should.eql(1) + heap.toArray().sort().should.eql([2..6]) + +describe 'Heap#contains', -> + it 'should return whether it contains the value', -> + heap = new Heap + heap.push(v) for v in [1..5] + heap.contains(v).should.be.true for v in [1..5] + heap.contains(0).should.be.false + heap.contains(6).should.be.false + +describe 'Heap#peek', -> + it 'should return the top value', -> + heap = new Heap + heap.push(1) + heap.peek().should.eql(1) + heap.push(2) + heap.peek().should.eql(1) + heap.pop() + heap.peek().should.eql(2) + +describe 'Heap#clone', -> + it 'should return a cloned heap', -> + a = new Heap + a.push(v) for v in [1..5] + b = a.clone() + a.toArray().should.eql(b.toArray()) + +describe 'Heap.nsmallest', -> + it 'should return exactly n elements when size() >= n', -> + Heap.nsmallest([1..10], 3).should.eql([1..3]) + + array = [1,3,2,1,3,4,4,2,3,4,5,1,2,3,4,5,2,1,3,4,5,6,7,2] + Heap.nsmallest(array, 2).should.eql([1, 1]) + + it 'should return size() elements when size() <= n', -> + Heap.nsmallest([3..1], 10).should.eql([1..3]) + +describe 'Heap.nlargest', -> + it 'should return exactly n elements when size() >= n', -> + Heap.nlargest([1..10], 3).should.eql([10..8]) + + it 'should return size() elements when size() <= n', -> + Heap.nlargest([3..1], 10).should.eql([3..1]) + +describe 'Heap#updateItem', -> + it 'should return correct order', -> + a = x: 1 + b = x: 2 + c = x: 3 + h = new Heap (m, n) -> m.x - n.x + h.push(a) + h.push(b) + h.push(c) + c.x = 0 + h.updateItem(c) + h.pop().should.eql(c) + it 'should return correct order when used statically', -> + a = x: 1 + b = x: 2 + c = x: 3 + h = [] + cmp = (m, n) -> m.x - n.x + Heap.push(h, a, cmp) + Heap.push(h, b, cmp) + Heap.push(h, c, cmp) + c.x = 0 + Heap.updateItem(h, c, cmp) + Heap.pop(h, cmp).should.eql(c) diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +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/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/node-domexception/.history/README_20210527203617.md b/node_modules/node-domexception/.history/README_20210527203617.md new file mode 100644 index 0000000..38d8f85 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527203617.md @@ -0,0 +1,2 @@ +# node-domexception +An implementation of the DOMException class from NodeJS diff --git a/node_modules/node-domexception/.history/README_20210527212714.md b/node_modules/node-domexception/.history/README_20210527212714.md new file mode 100644 index 0000000..eed1d13 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527212714.md @@ -0,0 +1,41 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMexception provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' + +hello().catch(err => { + if (err instanceof DOMException) { + ... + } +}) + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); +``` + +## APIs + +This package exposes two flavors of the `DOMException` interface depending on the imported module. + +### `domexception` module + +This module default-exports the `DOMException` interface constructor. + +### `domexception/webidl2js-wrapper` module + +This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). diff --git a/node_modules/node-domexception/.history/README_20210527213345.md b/node_modules/node-domexception/.history/README_20210527213345.md new file mode 100644 index 0000000..5825416 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213345.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527213411.md b/node_modules/node-domexception/.history/README_20210527213411.md new file mode 100644 index 0000000..4c21ec8 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213411.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527213803.md b/node_modules/node-domexception/.history/README_20210527213803.md new file mode 100644 index 0000000..4cb8571 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213803.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527214323.md b/node_modules/node-domexception/.history/README_20210527214323.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527214323.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527214408.md b/node_modules/node-domexception/.history/README_20210527214408.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527214408.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/index_20210527203842.js b/node_modules/node-domexception/.history/index_20210527203842.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-domexception/.history/index_20210527203947.js b/node_modules/node-domexception/.history/index_20210527203947.js new file mode 100644 index 0000000..b9a8b76 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527203947.js @@ -0,0 +1,8 @@ +const { MessageChannel } = require('worker_threads') + +if (!globalThis.DOMException) { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} diff --git a/node_modules/node-domexception/.history/index_20210527204259.js b/node_modules/node-domexception/.history/index_20210527204259.js new file mode 100644 index 0000000..e9332a8 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204259.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports diff --git a/node_modules/node-domexception/.history/index_20210527204418.js b/node_modules/node-domexception/.history/index_20210527204418.js new file mode 100644 index 0000000..cb362cc --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204418.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527204756.js b/node_modules/node-domexception/.history/index_20210527204756.js new file mode 100644 index 0000000..87d2655 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204756.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527204833.js b/node_modules/node-domexception/.history/index_20210527204833.js new file mode 100644 index 0000000..837ebda --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204833.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527211208.js b/node_modules/node-domexception/.history/index_20210527211208.js new file mode 100644 index 0000000..ba215ce --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527211208.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + var { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527211248.js b/node_modules/node-domexception/.history/index_20210527211248.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527211248.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527212722.js b/node_modules/node-domexception/.history/index_20210527212722.js new file mode 100644 index 0000000..91b3b52 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212722.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); diff --git a/node_modules/node-domexception/.history/index_20210527212731.js b/node_modules/node-domexception/.history/index_20210527212731.js new file mode 100644 index 0000000..cf28864 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212731.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 2); diff --git a/node_modules/node-domexception/.history/index_20210527212746.js b/node_modules/node-domexception/.history/index_20210527212746.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212746.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527212900.js b/node_modules/node-domexception/.history/index_20210527212900.js new file mode 100644 index 0000000..efa2442 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212900.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213022.js b/node_modules/node-domexception/.history/index_20210527213022.js new file mode 100644 index 0000000..e59f047 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213022.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213822.js b/node_modules/node-domexception/.history/index_20210527213822.js new file mode 100644 index 0000000..7f4e13d --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213822.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213843.js b/node_modules/node-domexception/.history/index_20210527213843.js new file mode 100644 index 0000000..ee75b73 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213843.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213852.js b/node_modules/node-domexception/.history/index_20210527213852.js new file mode 100644 index 0000000..a82bee3 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213852.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213910.js b/node_modules/node-domexception/.history/index_20210527213910.js new file mode 100644 index 0000000..1e1ca29 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213910.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527214034.js b/node_modules/node-domexception/.history/index_20210527214034.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214034.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527214643.js b/node_modules/node-domexception/.history/index_20210527214643.js new file mode 100644 index 0000000..92ed847 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214643.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/node_modules/node-domexception/.history/index_20210527214654.js b/node_modules/node-domexception/.history/index_20210527214654.js new file mode 100644 index 0000000..6d5cb8e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214654.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 21) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/node_modules/node-domexception/.history/index_20210527214700.js b/node_modules/node-domexception/.history/index_20210527214700.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214700.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/package_20210527203733.json b/node_modules/node-domexception/.history/package_20210527203733.json new file mode 100644 index 0000000..5eeb306 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527203733.json @@ -0,0 +1,19 @@ +{ + "name": "domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527203825.json b/node_modules/node-domexception/.history/package_20210527203825.json new file mode 100644 index 0000000..4ca1713 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527203825.json @@ -0,0 +1,16 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527204621.json b/node_modules/node-domexception/.history/package_20210527204621.json new file mode 100644 index 0000000..3c414e9 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204621.json @@ -0,0 +1,19 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527204913.json b/node_modules/node-domexception/.history/package_20210527204913.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204913.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527204925.json b/node_modules/node-domexception/.history/package_20210527204925.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204925.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527205145.json b/node_modules/node-domexception/.history/package_20210527205145.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527205145.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527205156.json b/node_modules/node-domexception/.history/package_20210527205156.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527205156.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/test_20210527205603.js b/node_modules/node-domexception/.history/test_20210527205603.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-domexception/.history/test_20210527205957.js b/node_modules/node-domexception/.history/test_20210527205957.js new file mode 100644 index 0000000..73feac5 --- /dev/null +++ b/node_modules/node-domexception/.history/test_20210527205957.js @@ -0,0 +1,3 @@ +require('./index.js') + +console.log(DOMException.INDEX_SIZE_ERR) diff --git a/node_modules/node-domexception/.history/test_20210527210021.js b/node_modules/node-domexception/.history/test_20210527210021.js new file mode 100644 index 0000000..be47491 --- /dev/null +++ b/node_modules/node-domexception/.history/test_20210527210021.js @@ -0,0 +1,3 @@ +const e = require('./index.js') + +console.log(e.INDEX_SIZE_ERR) diff --git a/node_modules/node-domexception/LICENSE b/node_modules/node-domexception/LICENSE new file mode 100644 index 0000000..bc8ceb7 --- /dev/null +++ b/node_modules/node-domexception/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Jimmy Wärting + +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/node_modules/node-domexception/README.md b/node_modules/node-domexception/README.md new file mode 100644 index 0000000..a369461 --- /dev/null +++ b/node_modules/node-domexception/README.md @@ -0,0 +1,46 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the legacy codes) + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` + +# Background + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws a DOMException and catch the constructor. This is exactly what this package dose for you and exposes it.
+This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
+The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +The DOMException is used in many places such as the Fetch API, File & Blobs, PostMessaging and more.
+Why they decided to call it **DOM**, I don't know + +Please consider sponsoring if you find this helpful diff --git a/node_modules/node-domexception/index.js b/node_modules/node-domexception/index.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/index.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/package.json b/node_modules/node-domexception/package.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/package.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-fetch/@types/index.d.ts b/node_modules/node-fetch/@types/index.d.ts new file mode 100644 index 0000000..2374801 --- /dev/null +++ b/node_modules/node-fetch/@types/index.d.ts @@ -0,0 +1,218 @@ +/// + +import {RequestOptions} from 'http'; +import {FormData} from 'formdata-polyfill/esm.min.js'; +import { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync +} from 'fetch-blob/from.js'; + +type AbortSignal = { + readonly aborted: boolean; + + addEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void; + removeEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void; +}; + +export type HeadersInit = Headers | Record | Iterable | Iterable>; + +export { + FormData, + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync +}; + +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. + * These actions include retrieving, setting, adding to, and removing. + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. + * You can add to this using methods like append() (see Examples.) + * In all methods of this interface, header names are matched by case-insensitive byte sequence. + * */ +export class Headers { + constructor(init?: HeadersInit); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach( + callbackfn: (value: string, key: string, parent: Headers) => void, + thisArg?: any + ): void; + + [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all key/value pairs contained in this object. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. + */ + keys(): IterableIterator; + /** + * Returns an iterator allowing to go through all values of the key/value pairs contained in this object. + */ + values(): IterableIterator; + + /** Node-fetch extension */ + raw(): Record; +} + +export interface RequestInit { + /** + * A BodyInit object or null to set request's body. + */ + body?: BodyInit | null; + /** + * A Headers object, an object literal, or an array of two-item arrays to set request's headers. + */ + headers?: HeadersInit; + /** + * A string to set request's method. + */ + method?: string; + /** + * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. + */ + redirect?: RequestRedirect; + /** + * An AbortSignal to set request's signal. + */ + signal?: AbortSignal | null; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer. + */ + referrer?: string; + /** + * A referrer policy to set request’s referrerPolicy. + */ + referrerPolicy?: ReferrerPolicy; + + // Node-fetch extensions to the whatwg/fetch spec + agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']); + compress?: boolean; + counter?: number; + follow?: number; + hostname?: string; + port?: number; + protocol?: string; + size?: number; + highWaterMark?: number; + insecureHTTPParser?: boolean; +} + +export interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +export type BodyInit = + | Blob + | Buffer + | URLSearchParams + | FormData + | NodeJS.ReadableStream + | string; +declare class BodyMixin { + constructor(body?: BodyInit, options?: {size?: number}); + + readonly body: NodeJS.ReadableStream | null; + readonly bodyUsed: boolean; + readonly size: number; + + /** @deprecated Use `body.arrayBuffer()` instead. */ + buffer(): Promise; + arrayBuffer(): Promise; + formData(): Promise; + blob(): Promise; + json(): Promise; + text(): Promise; +} + +// `Body` must not be exported as a class since it's not exported from the JavaScript code. +export interface Body extends Pick {} + +export type RequestRedirect = 'error' | 'follow' | 'manual'; +export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; +export type RequestInfo = string | Request; +export class Request extends BodyMixin { + constructor(input: RequestInfo, init?: RequestInit); + + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + */ + readonly headers: Headers; + /** + * Returns request's HTTP method, which is "GET" by default. + */ + readonly method: string; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + */ + readonly redirect: RequestRedirect; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + */ + readonly signal: AbortSignal; + /** + * Returns the URL of request as a string. + */ + readonly url: string; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request’s referrer. + */ + readonly referrer: string; + /** + * A referrer policy to set request’s referrerPolicy. + */ + readonly referrerPolicy: ReferrerPolicy; + clone(): Request; +} + +type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'; + +export class Response extends BodyMixin { + constructor(body?: BodyInit | null, init?: ResponseInit); + + readonly headers: Headers; + readonly ok: boolean; + readonly redirected: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + clone(): Response; + + static error(): Response; + static redirect(url: string, status?: number): Response; +} + +export class FetchError extends Error { + constructor(message: string, type: string, systemError?: Record); + + name: 'FetchError'; + [Symbol.toStringTag]: 'FetchError'; + type: string; + code?: string; + errno?: string; +} + +export class AbortError extends Error { + type: string; + name: 'AbortError'; + [Symbol.toStringTag]: 'AbortError'; +} + +export function isRedirect(code: number): boolean; +export default function fetch(url: RequestInfo, init?: RequestInit): Promise; diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..41ca1b6 --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 - 2020 Node Fetch Team + +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/node_modules/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 0000000..dc6661e --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,871 @@ +
+ Node Fetch +
+

A light-weight module that brings Fetch API to Node.js.

+ Build status + Coverage status + Current version + Install size + Mentioned in Awesome Node.js + Discord +
+
+ Consider supporting us on our Open Collective: +
+
+ Open Collective +
+ +--- + +**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)** + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Upgrading](#upgrading) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) + - [Handling cookies](#handling-cookies) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file](#post-data-using-a-file) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Default Headers](#default-headers) + - [Custom Agent](#custom-agent) + - [Custom highWaterMark](#custom-highwatermark) + - [Insecure HTTP Parser](#insecure-http-parser) + - [Class: Request](#class-request) + - [new Request(input[, options])](#new-requestinput-options) + - [Class: Response](#class-response) + - [new Response([body[, options]])](#new-responsebody-options) + - [response.ok](#responseok) + - [response.redirected](#responseredirected) + - [response.type](#responsetype) + - [Class: Headers](#class-headers) + - [new Headers([init])](#new-headersinit) + - [Interface: Body](#interface-body) + - [body.body](#bodybody) + - [body.bodyUsed](#bodybodyused) + - [body.arrayBuffer()](#bodyarraybuffer) + - [body.blob()](#bodyblob) + - [body.formData()](#formdata) + - [body.json()](#bodyjson) + - [body.text()](#bodytext) + - [Class: FetchError](#class-fetcherror) + - [Class: AbortError](#class-aborterror) +- [TypeScript](#typescript) +- [Acknowledgement](#acknowledgement) +- [Team](#team) + - [Former](#former) +- [License](#license) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise and async functions. +- Use native Node streams for body, on both request and response. +- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting. + +## Difference from client-side fetch + +- See known differences: + - [As of v3.x](docs/v3-LIMITS.md) + - [As of v2.x](docs/v2-LIMITS.md) +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`3.x`) requires at least Node.js 12.20.0. + +```sh +npm install node-fetch +``` + +## Loading and configuring the module + +### ES Modules (ESM) + +```js +import fetch from 'node-fetch'; +``` + +### CommonJS + +`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`. + +If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2. + +```sh +npm install node-fetch@2 +``` + +Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously: + +```js +// mod.cjs +const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args)); +``` + +### Providing global access + +To use `fetch()` without importing it, you can patch the `global` object in node: + +```js +// fetch-polyfill.js +import fetch, { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync, + FormData, + Headers, + Request, + Response, +} from 'node-fetch' + +if (!globalThis.fetch) { + globalThis.fetch = fetch + globalThis.Headers = Headers + globalThis.Request = Request + globalThis.Response = Response +} + +// index.js +import './fetch-polyfill' + +// ... +``` + +## Upgrading + +Using an old version of node-fetch? Check out the following files: + +- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md) +- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md) +- [Changelog](https://github.com/node-fetch/node-fetch/releases) + +## Common Usage + +NOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading). + +### Plain text or HTML + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://github.com/'); +const body = await response.text(); + +console.log(body); +``` + +### JSON + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://api.github.com/users/github'); +const data = await response.json(); + +console.log(data); +``` + +### Simple Post + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'}); +const data = await response.json(); + +console.log(data); +``` + +### Post with JSON + +```js +import fetch from 'node-fetch'; + +const body = {a: 1}; + +const response = await fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: {'Content-Type': 'application/json'} +}); +const data = await response.json(); + +console.log(data); +``` + +### Post with form parameters + +`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +import fetch from 'node-fetch'; + +const params = new URLSearchParams(); +params.append('a', 1); + +const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params}); +const data = await response.json(); + +console.log(data); +``` + +### Handling exceptions + +NOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section. + +Wrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details. + +```js +import fetch from 'node-fetch'; + +try { + await fetch('https://domain.invalid/'); +} catch (error) { + console.log(error); +} +``` + +### Handling client and server errors + +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +import fetch from 'node-fetch'; + +class HTTPResponseError extends Error { + constructor(response, ...args) { + super(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args); + this.response = response; + } +} + +const checkStatus = response => { + if (response.ok) { + // response.status >= 200 && response.status < 300 + return response; + } else { + throw new HTTPResponseError(response); + } +} + +const response = await fetch('https://httpbin.org/status/400'); + +try { + checkStatus(response); +} catch (error) { + console.error(error); + + const errorBody = await error.response.text(); + console.error(`Error body: ${errorBody}`); +} +``` + +### Handling cookies + +Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details. + +## Advanced Usage + +### Streams + +The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete. + +```js +import {createWriteStream} from 'node:fs'; +import {pipeline} from 'node:stream'; +import {promisify} from 'node:util' +import fetch from 'node-fetch'; + +const streamPipeline = promisify(pipeline); + +const response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png'); + +if (!response.ok) throw new Error(`unexpected response ${response.statusText}`); + +await streamPipeline(response.body, createWriteStream('./octocat.png')); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://httpbin.org/stream/3'); + +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +import fetch from 'node-fetch'; + +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; + +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +### Accessing Headers and other Metadata + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://github.com/'); + +console.log(response.ok); +console.log(response.status); +console.log(response.statusText); +console.log(response.headers.raw()); +console.log(response.headers.get('content-type')); +``` + +### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com'); + +// Returns an array of values, instead of a string of comma-separated values +console.log(response.headers.raw()['set-cookie']); +``` + +### Post data using a file + +```js +import fetch { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync, +} from 'node-fetch' + +const mimetype = 'text/plain' +const blob = fileFromSync('./input.txt', mimetype) +const url = 'https://httpbin.org/post' + +const response = await fetch(url, { method: 'POST', body: blob }) +const data = await response.json() + +console.log(data) +``` + +node-fetch comes with a spec-compliant [FormData] implementations for posting +multipart/form-data payloads + +```js +import fetch, { FormData, File, fileFrom } from 'node-fetch' + +const httpbin = 'https://httpbin.org/post' +const formData = new FormData() +const binary = new Uint8Array([ 97, 98, 99 ]) +const abc = new File([binary], 'abc.txt', { type: 'text/plain' }) + +formData.set('greeting', 'Hello, world!') +formData.set('file-upload', abc, 'new name.txt') + +const response = await fetch(httpbin, { method: 'POST', body: formData }) +const data = await response.json() + +console.log(data) +``` + +If you for some reason need to post a stream coming from any arbitrary place, +then you can append a [Blob] or a [File] look-a-like item. + +The minimum requirement is that it has: +1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File` +2. A known size. +3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer. + +The `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer) +so Node.Readable streams and whatwg streams works just fine. + +```js +formData.append('upload', { + [Symbol.toStringTag]: 'Blob', + size: 3, + *stream() { + yield new Uint8Array([97, 98, 99]) + }, + arrayBuffer() { + return new Uint8Array([97, 98, 99]).buffer + } +}, 'abc.txt') +``` + +### Request cancellation with AbortSignal + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import fetch, { AbortError } from 'node-fetch'; + +// AbortController was added in node v14.17.0 globally +const AbortController = globalThis.AbortController || await import('abort-controller') + +const controller = new AbortController(); +const timeout = setTimeout(() => { + controller.abort(); +}, 150); + +try { + const response = await fetch('https://example.com', {signal: controller.signal}); + const data = await response.json(); +} catch (error) { + if (error instanceof AbortError) { + console.log('request was aborted'); + } +} finally { + clearTimeout(timeout); +} +``` + +See [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples. + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // Request body. can be null, or a Node.js Readable stream + redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // Pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null, // http(s).Agent instance or function that returns an instance (see below) + highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. + insecureHTTPParser: false // Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. +} +``` + +#### Default Headers + +If no values are set, the following request headers will be sent automatically: + +| Header | Value | +| ------------------- | ------------------------------------------------------ | +| `Accept-Encoding` | `gzip, deflate, br` (when `options.compress === true`) | +| `Accept` | `*/*` | +| `Connection` | `close` _(when no `options.agent` is present)_ | +| `Content-Length` | _(automatically calculated, if possible)_ | +| `Host` | _(host and port information from the target URI)_ | +| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ | +| `User-Agent` | `node-fetch` | + + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +#### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +import http from 'node:http'; +import https from 'node:https'; + +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function(_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +}; +``` + + + +#### Custom highWaterMark + +Stream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node. + +The recommended way to fix this problem is to resolve cloned response in parallel: + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com'); +const r1 = response.clone(); + +const results = await Promise.all([response.json(), r1.text()]); + +console.log(results[0]); +console.log(results[1]); +``` + +If for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option: + +```js +import fetch from 'node-fetch'; + +const response = await fetch('https://example.com', { + // About 1MB + highWaterMark: 1024 * 1024 +}); + +const result = await res.clone().arrayBuffer(); +console.dir(result); +``` + +#### Insecure HTTP Parser + +Passed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information. + +#### Manual Redirect + +The `redirect: 'manual'` option for node-fetch is different from the browser & specification, which +results in an [opaque-redirect filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect). +node-fetch gives you the typical [basic filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-basic) instead. + +```js +const fetch = require('node-fetch'); + +const response = await fetch('https://httpbin.org/status/301', { redirect: 'manual' }); + +if (response.status === 301 || response.status === 302) { + const locationURL = new URL(response.headers.get('location'), response.url); + const response2 = await fetch(locationURL, { redirect: 'manual' }); + console.dir(response2); +} +``` + + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` +- `highWaterMark` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +_(spec-compliant)_ + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options](#fetch-options) for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `trailer` + +#### new Response([body[, options]]) + +_(spec-compliant)_ + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +_(spec-compliant)_ + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +_(spec-compliant)_ + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + +#### response.type + +_(deviation from spec)_ + +Convenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response). + + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +_(spec-compliant)_ + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class +import {Headers} from 'node-fetch'; + +const meta = { + 'Content-Type': 'text/xml' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [['Content-Type', 'text/xml']]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +#### body.body + +_(deviation from spec)_ + +- Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +_(spec-compliant)_ + +- `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() + +#### body.formData() + +#### body.blob() + +#### body.json() + +#### body.text() + +`fetch` comes with methods to parse `multipart/form-data` payloads as well as +`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that +Service Worker can intercept such messages before it's sent to the server to +alter them. This is useful for anybody building a server so you can use it to +parse & consume payloads. + +
+Code example + +```js +import http from 'node:http' +import { Response } from 'node-fetch' + +http.createServer(async function (req, res) { + const formData = await new Response(req, { + headers: req.headers // Pass along the boundary value + }).formData() + const allFields = [...formData] + + const file = formData.get('uploaded-files') + const arrayBuffer = await file.arrayBuffer() + const text = await file.text() + const whatwgReadableStream = file.stream() + + // other was to consume the request could be to do: + const json = await new Response(req).json() + const text = await new Response(req).text() + const arrayBuffer = await new Response(req).arrayBuffer() + const blob = await new Response(req, { + headers: req.headers // So that `type` inherits `Content-Type` + }.blob() +}) +``` + +
+ + + +### Class: FetchError + +_(node-fetch extension)_ + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + + +### Class: AbortError + +_(node-fetch extension)_ + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## TypeScript + +**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.** + +For older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped): + +```sh +npm install --save-dev @types/node-fetch@2.x +``` + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +## Team + +| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) | +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | +| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.ch) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) | + +###### Former + +- [Timothy Gu](https://github.com/timothygu) +- [Jared Kantrowitz](https://github.com/jkantr) + +## License + +[MIT](LICENSE.md) + +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md +[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData +[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob +[File]: https://developer.mozilla.org/en-US/docs/Web/API/File diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 0000000..65dd37e --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,131 @@ +{ + "name": "node-fetch", + "version": "3.2.10", + "description": "A light-weight module that brings Fetch API to node.js", + "main": "./src/index.js", + "sideEffects": false, + "type": "module", + "files": [ + "src", + "@types/index.d.ts" + ], + "types": "./@types/index.d.ts", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "mocha", + "coverage": "c8 report --reporter=text-lcov | coveralls", + "test-types": "tsd", + "lint": "xo" + }, + "repository": { + "type": "git", + "url": "https://github.com/node-fetch/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/node-fetch/node-fetch/issues" + }, + "homepage": "https://github.com/node-fetch/node-fetch", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + }, + "devDependencies": { + "abort-controller": "^3.0.0", + "abortcontroller-polyfill": "^1.7.1", + "busboy": "^1.4.0", + "c8": "^7.7.2", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^3.0.2", + "chai-string": "^1.5.0", + "coveralls": "^3.1.0", + "form-data": "^4.0.0", + "formdata-node": "^4.2.4", + "mocha": "^9.1.3", + "p-timeout": "^5.0.0", + "stream-consumers": "^1.0.1", + "tsd": "^0.14.0", + "xo": "^0.39.1" + }, + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "tsd": { + "cwd": "@types", + "compilerOptions": { + "esModuleInterop": true + } + }, + "xo": { + "envs": [ + "node", + "browser" + ], + "ignores": [ + "example.js" + ], + "rules": { + "complexity": 0, + "import/extensions": 0, + "import/no-useless-path-segments": 0, + "import/no-anonymous-default-export": 0, + "import/no-named-as-default": 0, + "unicorn/import-index": 0, + "unicorn/no-array-reduce": 0, + "unicorn/prefer-node-protocol": 0, + "unicorn/numeric-separators-style": 0, + "unicorn/explicit-length-check": 0, + "capitalized-comments": 0, + "node/no-unsupported-features/es-syntax": 0, + "@typescript-eslint/member-ordering": 0 + }, + "overrides": [ + { + "files": "test/**/*.js", + "envs": [ + "node", + "mocha" + ], + "rules": { + "max-nested-callbacks": 0, + "no-unused-expressions": 0, + "no-warning-comments": 0, + "new-cap": 0, + "guard-for-in": 0, + "unicorn/no-array-for-each": 0, + "unicorn/prevent-abbreviations": 0, + "promise/prefer-await-to-then": 0, + "ava/no-import-test-files": 0 + } + } + ] + }, + "runkitExampleFilename": "example.js", + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/node_modules/node-fetch/src/body.js b/node_modules/node-fetch/src/body.js new file mode 100644 index 0000000..714e27e --- /dev/null +++ b/node_modules/node-fetch/src/body.js @@ -0,0 +1,397 @@ + +/** + * Body.js + * + * Body interface provides common methods for Request and Response + */ + +import Stream, {PassThrough} from 'node:stream'; +import {types, deprecate, promisify} from 'node:util'; +import {Buffer} from 'node:buffer'; + +import Blob from 'fetch-blob'; +import {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js'; + +import {FetchError} from './errors/fetch-error.js'; +import {FetchBaseError} from './errors/base.js'; +import {isBlob, isURLSearchParameters} from './utils/is.js'; + +const pipeline = promisify(Stream.pipeline); +const INTERNALS = Symbol('Body internals'); + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +export default class Body { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + + if (body === null) { + // Body is undefined or null + body = null; + } else if (isURLSearchParameters(body)) { + // Body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) { + // Body is blob + } else if (Buffer.isBuffer(body)) { + // Body is Buffer + } else if (types.isAnyArrayBuffer(body)) { + // Body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // Body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) { + // Body is stream + } else if (body instanceof FormData) { + // Body is FormData + body = formDataToBlob(body); + boundary = body.type.split('=')[1]; + } else { + // None of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + + let stream = body; + + if (Buffer.isBuffer(body)) { + stream = Stream.Readable.from(body); + } else if (isBlob(body)) { + stream = Stream.Readable.from(body.stream()); + } + + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + + if (body instanceof Stream) { + body.on('error', error_ => { + const error = error_ instanceof FetchBaseError ? + error_ : + new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); + this[INTERNALS].error = error; + }); + } + } + + get body() { + return this[INTERNALS].stream; + } + + get bodyUsed() { + return this[INTERNALS].disturbed; + } + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const {buffer, byteOffset, byteLength} = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + + async formData() { + const ct = this.headers.get('content-type'); + + if (ct.startsWith('application/x-www-form-urlencoded')) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + + for (const [name, value] of parameters) { + formData.append(name, value); + } + + return formData; + } + + const {toFormData} = await import('./utils/multipart-parser.js'); + return toFormData(this.body, ct); + } + + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || ''; + const buf = await this.arrayBuffer(); + + return new Blob([buf], { + type: ct + }); + } + + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +} + +Body.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: {enumerable: true}, + bodyUsed: {enumerable: true}, + arrayBuffer: {enumerable: true}, + blob: {enumerable: true}, + json: {enumerable: true}, + text: {enumerable: true}, + data: {get: deprecate(() => {}, + 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')} +}); + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + + data[INTERNALS].disturbed = true; + + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + + const {body} = data; + + // Body is null + if (body === null) { + return Buffer.alloc(0); + } + + /* c8 ignore next 3 */ + if (!(body instanceof Stream)) { + return Buffer.alloc(0); + } + + // Body is stream + // get ready to actually consume the body + const accum = []; + let accumBytes = 0; + + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size'); + body.destroy(error); + throw error; + } + + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error); + throw error_; + } + + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every(c => typeof c === 'string')) { + return Buffer.from(accum.join('')); + } + + return Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} + +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @param String highWaterMark highWaterMark for both PassThrough body streams + * @return Mixed + */ +export const clone = (instance, highWaterMark) => { + let p1; + let p2; + let {body} = instance[INTERNALS]; + + // Don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } + + // Check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) { + // Tee instance body + p1 = new PassThrough({highWaterMark}); + p2 = new PassThrough({highWaterMark}); + body.pipe(p1); + body.pipe(p2); + // Set instance body to teed body and return the other teed body + instance[INTERNALS].stream = p1; + body = p2; + } + + return body; +}; + +const getNonSpecFormDataBoundary = deprecate( + body => body.getBoundary(), + 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package', + 'https://github.com/node-fetch/node-fetch/issues/1167' +); + +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param {any} body Any options.body input + * @returns {string | null} + */ +export const extractContentType = (body, request) => { + // Body is null or undefined + if (body === null) { + return null; + } + + // Body is string + if (typeof body === 'string') { + return 'text/plain;charset=UTF-8'; + } + + // Body is a URLSearchParams + if (isURLSearchParameters(body)) { + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } + + // Body is blob + if (isBlob(body)) { + return body.type || null; + } + + // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView) + if (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; + } + + // Detect form data input from form-data module + if (body && typeof body.getBoundary === 'function') { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + + // Body is stream - can't really do much about this + if (body instanceof Stream) { + return null; + } + + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; +}; + +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param {any} obj.body Body object from the Body instance. + * @returns {number | null} + */ +export const getTotalBytes = request => { + const {body} = request[INTERNALS]; + + // Body is null or undefined + if (body === null) { + return 0; + } + + // Body is Blob + if (isBlob(body)) { + return body.size; + } + + // Body is Buffer + if (Buffer.isBuffer(body)) { + return body.length; + } + + // Detect form data input from form-data module + if (body && typeof body.getLengthSync === 'function') { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + + // Body is stream + return null; +}; + +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param {Stream.Writable} dest The stream to write to. + * @param obj.body Body object from the Body instance. + * @returns {Promise} + */ +export const writeToStream = async (dest, {body}) => { + if (body === null) { + // Body is null + dest.end(); + } else { + // Body is stream + await pipeline(body, dest); + } +}; diff --git a/node_modules/node-fetch/src/errors/abort-error.js b/node_modules/node-fetch/src/errors/abort-error.js new file mode 100644 index 0000000..0b62f1c --- /dev/null +++ b/node_modules/node-fetch/src/errors/abort-error.js @@ -0,0 +1,10 @@ +import {FetchBaseError} from './base.js'; + +/** + * AbortError interface for cancelled requests + */ +export class AbortError extends FetchBaseError { + constructor(message, type = 'aborted') { + super(message, type); + } +} diff --git a/node_modules/node-fetch/src/errors/base.js b/node_modules/node-fetch/src/errors/base.js new file mode 100644 index 0000000..4e66e1b --- /dev/null +++ b/node_modules/node-fetch/src/errors/base.js @@ -0,0 +1,17 @@ +export class FetchBaseError extends Error { + constructor(message, type) { + super(message); + // Hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); + + this.type = type; + } + + get name() { + return this.constructor.name; + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } +} diff --git a/node_modules/node-fetch/src/errors/fetch-error.js b/node_modules/node-fetch/src/errors/fetch-error.js new file mode 100644 index 0000000..f7ae5cc --- /dev/null +++ b/node_modules/node-fetch/src/errors/fetch-error.js @@ -0,0 +1,26 @@ + +import {FetchBaseError} from './base.js'; + +/** + * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError +*/ + +/** + * FetchError interface for operational errors + */ +export class FetchError extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code + if (systemError) { + // eslint-disable-next-line no-multi-assign + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +} diff --git a/node_modules/node-fetch/src/headers.js b/node_modules/node-fetch/src/headers.js new file mode 100644 index 0000000..cd69455 --- /dev/null +++ b/node_modules/node-fetch/src/headers.js @@ -0,0 +1,267 @@ +/** + * Headers.js + * + * Headers class offers convenient helpers + */ + +import {types} from 'node:util'; +import http from 'node:http'; + +/* c8 ignore next 9 */ +const validateHeaderName = typeof http.validateHeaderName === 'function' ? + http.validateHeaderName : + name => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'}); + throw error; + } + }; + +/* c8 ignore next 9 */ +const validateHeaderValue = typeof http.validateHeaderValue === 'function' ? + http.validateHeaderValue : + (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'}); + throw error; + } + }; + +/** + * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit + */ + +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. + * These actions include retrieving, setting, adding to, and removing. + * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. + * You can add to this using methods like append() (see Examples.) + * In all methods of this interface, header names are matched by case-insensitive byte sequence. + * + */ +export default class Headers extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + // Validate and normalize init object in [name, value(s)][] + /** @type {string[][]} */ + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map(value => [name, value])); + } + } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq + // No op + } else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + // eslint-disable-next-line no-eq-null, eqeqeq + if (method == null) { + // Record + result.push(...Object.entries(init)); + } else { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // Sequence> + // Note: per spec we have to first exhaust the lists then process them + result = [...init] + .map(pair => { + if ( + typeof pair !== 'object' || types.isBoxedPrimitive(pair) + ) { + throw new TypeError('Each header pair must be an iterable object'); + } + + return [...pair]; + }).map(pair => { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + + return [...pair]; + }); + } + } else { + throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)'); + } + + // Validate and lowercase + result = + result.length > 0 ? + result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : + undefined; + + super(result); + + // Returning a Proxy that will lowercase key names, validate parameters and sort keys + // eslint-disable-next-line no-constructor-return + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case 'append': + case 'set': + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + + case 'delete': + case 'has': + case 'getAll': + return name => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + + case 'keys': + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + + default: + return Reflect.get(target, p, receiver); + } + } + }); + /* c8 ignore next */ + } + + get [Symbol.toStringTag]() { + return this.constructor.name; + } + + toString() { + return Object.prototype.toString.call(this); + } + + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + + let value = values.join(', '); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + + return value; + } + + forEach(callback, thisArg = undefined) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + + * values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + + /** + * @type {() => IterableIterator<[string, string]>} + */ + * entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + + [Symbol.iterator]() { + return this.entries(); + } + + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for('nodejs.util.inspect.custom')]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + // Http.request() only supports string as Host header. + // This hack makes specifying custom Host header possible. + if (key === 'host') { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + + return result; + }, {}); + } +} + +/** + * Re-shaping object for Web IDL tests + * Only need to do it for overridden methods + */ +Object.defineProperties( + Headers.prototype, + ['get', 'entries', 'forEach', 'values'].reduce((result, property) => { + result[property] = {enumerable: true}; + return result; + }, {}) +); + +/** + * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do + * not conform to HTTP grammar productions. + * @param {import('http').IncomingMessage['rawHeaders']} headers + */ +export function fromRawHeaders(headers = []) { + return new Headers( + headers + // Split into pairs + .reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + + return result; + }, []) + .filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + + ); +} diff --git a/node_modules/node-fetch/src/index.js b/node_modules/node-fetch/src/index.js new file mode 100644 index 0000000..7c4aee8 --- /dev/null +++ b/node_modules/node-fetch/src/index.js @@ -0,0 +1,417 @@ +/** + * Index.js + * + * a request API compatible with window.fetch + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + +import http from 'node:http'; +import https from 'node:https'; +import zlib from 'node:zlib'; +import Stream, {PassThrough, pipeline as pump} from 'node:stream'; +import {Buffer} from 'node:buffer'; + +import dataUriToBuffer from 'data-uri-to-buffer'; + +import {writeToStream, clone} from './body.js'; +import Response from './response.js'; +import Headers, {fromRawHeaders} from './headers.js'; +import Request, {getNodeRequestOptions} from './request.js'; +import {FetchError} from './errors/fetch-error.js'; +import {AbortError} from './errors/abort-error.js'; +import {isRedirect} from './utils/is-redirect.js'; +import {FormData} from 'formdata-polyfill/esm.min.js'; +import {isDomainOrSubdomain, isSameProtocol} from './utils/is.js'; +import {parseReferrerPolicyFromHeader} from './utils/referrer.js'; +import { + Blob, + File, + fileFromSync, + fileFrom, + blobFromSync, + blobFrom +} from 'fetch-blob/from.js'; + +export {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect}; +export {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom}; + +const supportedSchemas = new Set(['data:', 'http:', 'https:']); + +/** + * Fetch function + * + * @param {string | URL | import('./request').default} url - Absolute url or Request instance + * @param {*} [options_] - Fetch options + * @return {Promise} + */ +export default async function fetch(url, options_) { + return new Promise((resolve, reject) => { + // Build request object + const request = new Request(url, options_); + const {parsedURL, options} = getNodeRequestOptions(request); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`); + } + + if (parsedURL.protocol === 'data:') { + const data = dataUriToBuffer(request.url); + const response = new Response(data, {headers: {'Content-Type': data.typeFull}}); + resolve(response); + return; + } + + // Wrap http.request into fetch + const send = (parsedURL.protocol === 'https:' ? https : http).request; + const {signal} = request; + let response = null; + + const abort = () => { + const error = new AbortError('The operation was aborted.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + + if (!response || !response.body) { + return; + } + + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = () => { + abort(); + finalize(); + }; + + // Send request + const request_ = send(parsedURL.toString(), options); + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener('abort', abortAndFinalize); + } + }; + + request_.on('error', error => { + reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error)); + finalize(); + }); + + fixResponseChunkedTransferBadEnding(request_, error => { + if (response && response.body) { + response.body.destroy(error); + } + }); + + /* c8 ignore next 18 */ + if (process.version < 'v14') { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + request_.on('socket', s => { + let endedWithEventsCount; + s.prependListener('end', () => { + endedWithEventsCount = s._eventsCount; + }); + s.prependListener('close', hadError => { + // if end happened before close but the socket didn't emit an error, do it now + if (response && endedWithEventsCount < s._eventsCount && !hadError) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', error); + } + }); + }); + } + + request_.on('response', response_ => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + + // HTTP fetch step 5 + if (isRedirect(response_.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request.url); + } catch { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // Nothing to do + break; + case 'follow': { + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOptions = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone(request), + signal: request.signal, + size: request.size, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy + }; + + // when forwarding sensitive headers like "Authorization", + // "WWW-Authenticate", and "Cookie" to untrusted targets, + // headers will be ignored when following a redirect to a domain + // that is not a subdomain match or exact match of the initial domain. + // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + // will forward the sensitive headers, but a redirect to "bar.com" will not. + // headers will also be ignored when following a redirect to a domain using + // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" + // will not forward the sensitive headers + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOptions.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) { + requestOptions.method = 'GET'; + requestOptions.body = undefined; + requestOptions.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 14 + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + + default: + return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); + } + } + + // Prepare response + if (signal) { + response_.once('end', () => { + signal.removeEventListener('abort', abortAndFinalize); + }); + } + + let body = pump(response_, new PassThrough(), error => { + if (error) { + reject(error); + } + }); + // see https://github.com/nodejs/node/pull/29376 + /* c8 ignore next 3 */ + if (process.version < 'v12.10') { + response_.on('aborted', abortAndFinalize); + } + + const responseOptions = { + url: request.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request.size, + counter: request.counter, + highWaterMark: request.highWaterMark + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // For gzip + if (codings === 'gzip' || codings === 'x-gzip') { + body = pump(body, zlib.createGunzip(zlibOptions), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For deflate + if (codings === 'deflate' || codings === 'x-deflate') { + // Handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = pump(response_, new PassThrough(), error => { + if (error) { + reject(error); + } + }); + raw.once('data', chunk => { + // See http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = pump(body, zlib.createInflate(), error => { + if (error) { + reject(error); + } + }); + } else { + body = pump(body, zlib.createInflateRaw(), error => { + if (error) { + reject(error); + } + }); + } + + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once('end', () => { + // Some old IIS servers return zero-length OK deflate responses, so + // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + + // For br + if (codings === 'br') { + body = pump(body, zlib.createBrotliDecompress(), error => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // Otherwise, use response as-is + response = new Response(body, responseOptions); + resolve(response); + }); + + // eslint-disable-next-line promise/prefer-await-to-then + writeToStream(request_, request).catch(reject); + }); +} + +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + const LAST_CHUNK = Buffer.from('0\r\n\r\n'); + + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + + request.on('response', response => { + const {headers} = response; + isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length']; + }); + + request.on('socket', socket => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error('Premature close'); + error.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(error); + } + }; + + const onData = buf => { + properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + + // Sometimes final 0-length chunk and end of message code are in separate packets + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = ( + Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 + ); + } + + previousChunk = buf; + }; + + socket.prependListener('close', onSocketClose); + socket.on('data', onData); + + request.on('close', () => { + socket.removeListener('close', onSocketClose); + socket.removeListener('data', onData); + }); + }); +} diff --git a/node_modules/node-fetch/src/request.js b/node_modules/node-fetch/src/request.js new file mode 100644 index 0000000..7a1a954 --- /dev/null +++ b/node_modules/node-fetch/src/request.js @@ -0,0 +1,317 @@ +/** + * Request.js + * + * Request class contains server only options + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + +import {format as formatUrl} from 'node:url'; +import {deprecate} from 'node:util'; +import Headers from './headers.js'; +import Body, {clone, extractContentType, getTotalBytes} from './body.js'; +import {isAbortSignal} from './utils/is.js'; +import {getSearch} from './utils/get-search.js'; +import { + validateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY +} from './utils/referrer.js'; + +const INTERNALS = Symbol('Request internals'); + +/** + * Check if `obj` is an instance of Request. + * + * @param {*} object + * @return {boolean} + */ +const isRequest = object => { + return ( + typeof object === 'object' && + typeof object[INTERNALS] === 'object' + ); +}; + +const doBadDataWarn = deprecate(() => {}, + '.data is not a valid RequestInit property, use .body instead', + 'https://github.com/node-fetch/node-fetch/issues/1000 (request)'); + +/** + * Request class + * + * Ref: https://fetch.spec.whatwg.org/#request-class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +export default class Request extends Body { + constructor(input, init = {}) { + let parsedURL; + + // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245) + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + + if (parsedURL.username !== '' || parsedURL.password !== '') { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + + let method = init.method || input.method || 'GET'; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + + if (!isRequest(init) && 'data' in init) { + doBadDataWarn(); + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if ((init.body != null || (isRequest(input) && input.body !== null)) && + (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + const inputBody = init.body ? + init.body : + (isRequest(input) && input.body !== null ? + clone(input) : + null); + + super(inputBody, { + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? + input.signal : + null; + if ('signal' in init) { + signal = init.signal; + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget'); + } + + // §5.4, Request constructor steps, step 15.1 + // eslint-disable-next-line no-eq-null, eqeqeq + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === '') { + // §5.4, Request constructor steps, step 15.2 + referrer = 'no-referrer'; + } else if (referrer) { + // §5.4, Request constructor steps, step 15.3.1, 15.3.2 + const parsedReferrer = new URL(referrer); + // §5.4, Request constructor steps, step 15.3.3, 15.3.4 + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer; + } else { + referrer = undefined; + } + + this[INTERNALS] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal, + referrer + }; + + // Node-fetch-only options + this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow; + this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + + // §5.4, Request constructor steps, step 16. + // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ''; + } + + /** @returns {string} */ + get method() { + return this[INTERNALS].method; + } + + /** @returns {string} */ + get url() { + return formatUrl(this[INTERNALS].parsedURL); + } + + /** @returns {Headers} */ + get headers() { + return this[INTERNALS].headers; + } + + get redirect() { + return this[INTERNALS].redirect; + } + + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS].signal; + } + + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS].referrer === 'no-referrer') { + return ''; + } + + if (this[INTERNALS].referrer === 'client') { + return 'about:client'; + } + + if (this[INTERNALS].referrer) { + return this[INTERNALS].referrer.toString(); + } + + return undefined; + } + + get referrerPolicy() { + return this[INTERNALS].referrerPolicy; + } + + set referrerPolicy(referrerPolicy) { + this[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + + get [Symbol.toStringTag]() { + return 'Request'; + } +} + +Object.defineProperties(Request.prototype, { + method: {enumerable: true}, + url: {enumerable: true}, + headers: {enumerable: true}, + redirect: {enumerable: true}, + clone: {enumerable: true}, + signal: {enumerable: true}, + referrer: {enumerable: true}, + referrerPolicy: {enumerable: true} +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param {Request} request - A Request instance + * @return The options object to be passed to http.request + */ +export const getNodeRequestOptions = request => { + const {parsedURL} = request[INTERNALS]; + const headers = new Headers(request[INTERNALS].headers); + + // Fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body === null && /^(post|put)$/i.test(request.method)) { + contentLengthValue = '0'; + } + + if (request.body !== null) { + const totalBytes = getTotalBytes(request); + // Set Content-Length if totalBytes is a number (that is not NaN) + if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // 4.1. Main fetch, step 2.6 + // > If request's referrer policy is the empty string, then set request's referrer policy to the + // > default referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + + // 4.1. Main fetch, step 2.7 + // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking + // > determine request's referrer. + if (request.referrer && request.referrer !== 'no-referrer') { + request[INTERNALS].referrer = determineRequestsReferrer(request); + } else { + request[INTERNALS].referrer = 'no-referrer'; + } + + // 4.5. HTTP-network-or-cache fetch, step 6.9 + // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized + // > and isomorphic encoded, to httpRequest's header list. + if (request[INTERNALS].referrer instanceof URL) { + headers.set('Referer', request.referrer); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip, deflate, br'); + } + + let {agent} = request; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + const search = getSearch(parsedURL); + + // Pass the full URL directly to request(), but overwrite the following + // options: + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request.method, + headers: headers[Symbol.for('nodejs.util.inspect.custom')](), + insecureHTTPParser: request.insecureHTTPParser, + agent + }; + + return { + /** @type {URL} */ + parsedURL, + options + }; +}; diff --git a/node_modules/node-fetch/src/response.js b/node_modules/node-fetch/src/response.js new file mode 100644 index 0000000..63af267 --- /dev/null +++ b/node_modules/node-fetch/src/response.js @@ -0,0 +1,141 @@ +/** + * Response.js + * + * Response class provides content decoding + */ + +import Headers from './headers.js'; +import Body, {clone, extractContentType} from './body.js'; +import {isRedirect} from './utils/is-redirect.js'; + +const INTERNALS = Symbol('Response internals'); + +/** + * Response class + * + * Ref: https://fetch.spec.whatwg.org/#response-class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +export default class Response extends Body { + constructor(body = null, options = {}) { + super(body, options); + + // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition + const status = options.status != null ? options.status : 200; + + const headers = new Headers(options.headers); + + if (body !== null && !headers.has('Content-Type')) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS] = { + type: 'default', + url: options.url, + status, + statusText: options.statusText || '', + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + + get type() { + return this[INTERNALS].type; + } + + get url() { + return this[INTERNALS].url || ''; + } + + get status() { + return this[INTERNALS].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300; + } + + get redirected() { + return this[INTERNALS].counter > 0; + } + + get statusText() { + return this[INTERNALS].statusText; + } + + get headers() { + return this[INTERNALS].headers; + } + + get highWaterMark() { + return this[INTERNALS].highWaterMark; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + + return new Response(null, { + headers: { + location: new URL(url).toString() + }, + status + }); + } + + static error() { + const response = new Response(null, {status: 0, statusText: ''}); + response[INTERNALS].type = 'error'; + return response; + } + + get [Symbol.toStringTag]() { + return 'Response'; + } +} + +Object.defineProperties(Response.prototype, { + type: {enumerable: true}, + url: {enumerable: true}, + status: {enumerable: true}, + ok: {enumerable: true}, + redirected: {enumerable: true}, + statusText: {enumerable: true}, + headers: {enumerable: true}, + clone: {enumerable: true} +}); diff --git a/node_modules/node-fetch/src/utils/get-search.js b/node_modules/node-fetch/src/utils/get-search.js new file mode 100644 index 0000000..d067e7c --- /dev/null +++ b/node_modules/node-fetch/src/utils/get-search.js @@ -0,0 +1,9 @@ +export const getSearch = parsedURL => { + if (parsedURL.search) { + return parsedURL.search; + } + + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : ''); + return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : ''; +}; diff --git a/node_modules/node-fetch/src/utils/is-redirect.js b/node_modules/node-fetch/src/utils/is-redirect.js new file mode 100644 index 0000000..d1347f0 --- /dev/null +++ b/node_modules/node-fetch/src/utils/is-redirect.js @@ -0,0 +1,11 @@ +const redirectStatus = new Set([301, 302, 303, 307, 308]); + +/** + * Redirect code matching + * + * @param {number} code - Status code + * @return {boolean} + */ +export const isRedirect = code => { + return redirectStatus.has(code); +}; diff --git a/node_modules/node-fetch/src/utils/is.js b/node_modules/node-fetch/src/utils/is.js new file mode 100644 index 0000000..f9e467e --- /dev/null +++ b/node_modules/node-fetch/src/utils/is.js @@ -0,0 +1,87 @@ +/** + * Is.js + * + * Object type checks. + */ + +const NAME = Symbol.toStringTag; + +/** + * Check if `obj` is a URLSearchParams object + * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143 + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isURLSearchParameters = object => { + return ( + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + typeof object.sort === 'function' && + object[NAME] === 'URLSearchParams' + ); +}; + +/** + * Check if `object` is a W3C `Blob` object (which `File` inherits from) + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isBlob = object => { + return ( + object && + typeof object === 'object' && + typeof object.arrayBuffer === 'function' && + typeof object.type === 'string' && + typeof object.stream === 'function' && + typeof object.constructor === 'function' && + /^(Blob|File)$/.test(object[NAME]) + ); +}; + +/** + * Check if `obj` is an instance of AbortSignal. + * @param {*} object - Object to check for + * @return {boolean} + */ +export const isAbortSignal = object => { + return ( + typeof object === 'object' && ( + object[NAME] === 'AbortSignal' || + object[NAME] === 'EventTarget' + ) + ); +}; + +/** + * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of + * the parent domain. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +export const isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + + return orig === dest || orig.endsWith(`.${dest}`); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +export const isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + + return orig === dest; +}; diff --git a/node_modules/node-fetch/src/utils/multipart-parser.js b/node_modules/node-fetch/src/utils/multipart-parser.js new file mode 100644 index 0000000..5ad06f9 --- /dev/null +++ b/node_modules/node-fetch/src/utils/multipart-parser.js @@ -0,0 +1,432 @@ +import {File} from 'fetch-blob/from.js'; +import {FormData} from 'formdata-polyfill/esm.min.js'; + +let s = 0; +const S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ +}; + +let f = 1; +const F = { + PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 +}; + +const LF = 10; +const CR = 13; +const SPACE = 32; +const HYPHEN = 45; +const COLON = 58; +const A = 97; +const Z = 122; + +const lower = c => c | 0x20; + +const noop = () => {}; + +class MultipartParser { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + + this.boundaryChars = {}; + + boundary = '\r\n--' + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i = 0; i < boundary.length; i++) { + ui8a[i] = boundary.charCodeAt(i); + this.boundaryChars[ui8a[i]] = true; + } + + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + + /** + * @param {Uint8Array} data + */ + write(data) { + let i = 0; + const length_ = data.length; + let previousIndex = this.index; + let {lookbehind, boundary, boundaryChars, index, state, flags} = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + + const mark = name => { + this[name + 'Mark'] = i; + }; + + const clear = name => { + delete this[name + 'Mark']; + }; + + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + + const dataCallback = (name, clear) => { + const markSymbol = name + 'Mark'; + if (!(markSymbol in this)) { + return; + } + + if (clear) { + callback(name, this[markSymbol], i, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + + for (i = 0; i < length_; i++) { + c = data[i]; + + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + } else { + return; + } + + break; + } + + if (c !== boundary[index + 2]) { + index = -2; + } + + if (c === boundary[index + 2]) { + index++; + } + + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('onHeaderField'); + index = 0; + // falls through + case S.HEADER_FIELD: + if (c === CR) { + clear('onHeaderField'); + state = S.HEADERS_ALMOST_DONE; + break; + } + + index++; + if (c === HYPHEN) { + break; + } + + if (c === COLON) { + if (index === 1) { + // empty header field + return; + } + + dataCallback('onHeaderField', true); + state = S.HEADER_VALUE_START; + break; + } + + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + + mark('onHeaderValue'); + state = S.HEADER_VALUE; + // falls through + case S.HEADER_VALUE: + if (c === CR) { + dataCallback('onHeaderValue', true); + callback('onHeaderEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + + callback('onHeadersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('onPartData'); + // falls through + case S.PART_DATA: + previousIndex = index; + + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(data[i] in boundaryChars)) { + i += boundaryLength; + } + + i -= boundaryEnd; + c = data[i]; + } + + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback('onPartData', true); + } + + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('onPartEnd'); + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback('onPartEnd'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + + if (index > 0) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback('onPartData', 0, previousIndex, _lookbehind); + previousIndex = 0; + mark('onPartData'); + + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } + + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + + dataCallback('onHeaderField'); + dataCallback('onHeaderValue'); + dataCallback('onPartData'); + + // Update properties for the next call + this.index = index; + this.state = state; + this.flags = flags; + } + + end() { + if ((this.state === S.HEADER_FIELD_START && this.index === 0) || + (this.state === S.PART_DATA && this.index === this.boundary.length)) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error('MultipartParser.end(): stream ended unexpectedly'); + } + } +} + +function _fileName(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m) { + return; + } + + const match = m[2] || m[3] || ''; + let filename = match.slice(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m, code) => { + return String.fromCharCode(code); + }); + return filename; +} + +export async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError('Failed to fetch'); + } + + const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + if (!m) { + throw new TypeError('no or bad content-type header, no multipart boundary'); + } + + const parser = new MultipartParser(m[1] || m[2]); + + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + + const onPartData = ui8a => { + entryValue += decoder.decode(ui8a, {stream: true}); + }; + + const appendToFile = ui8a => { + entryChunks.push(ui8a); + }; + + const appendFileToFormData = () => { + const file = new File(entryChunks, filename, {type: contentType}); + formData.append(entryName, file); + }; + + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + + const decoder = new TextDecoder('utf-8'); + decoder.decode(); + + parser.onPartBegin = function () { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + + headerField = ''; + headerValue = ''; + entryValue = ''; + entryName = ''; + contentType = ''; + filename = null; + entryChunks.length = 0; + }; + + parser.onHeaderField = function (ui8a) { + headerField += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderValue = function (ui8a) { + headerValue += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderEnd = function () { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + + if (headerField === 'content-disposition') { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + + if (m) { + entryName = m[2] || m[3] || ''; + } + + filename = _fileName(headerValue); + + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === 'content-type') { + contentType = headerValue; + } + + headerValue = ''; + headerField = ''; + }; + + for await (const chunk of Body) { + parser.write(chunk); + } + + parser.end(); + + return formData; +} diff --git a/node_modules/node-fetch/src/utils/referrer.js b/node_modules/node-fetch/src/utils/referrer.js new file mode 100644 index 0000000..6741f2f --- /dev/null +++ b/node_modules/node-fetch/src/utils/referrer.js @@ -0,0 +1,340 @@ +import {isIP} from 'node:net'; + +/** + * @external URL + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL} + */ + +/** + * @module utils/referrer + * @private + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer} + * @param {string} URL + * @param {boolean} [originOnly=false] + */ +export function stripURLForUseAsAReferrer(url, originOnly = false) { + // 1. If url is null, return no referrer. + if (url == null) { // eslint-disable-line no-eq-null, eqeqeq + return 'no-referrer'; + } + + url = new URL(url); + + // 2. If url's scheme is a local scheme, then return no referrer. + if (/^(about|blob|data):$/.test(url.protocol)) { + return 'no-referrer'; + } + + // 3. Set url's username to the empty string. + url.username = ''; + + // 4. Set url's password to null. + // Note: `null` appears to be a mistake as this actually results in the password being `"null"`. + url.password = ''; + + // 5. Set url's fragment to null. + // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`. + url.hash = ''; + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 6.1. Set url's path to null. + // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`. + url.pathname = ''; + + // 6.2. Set url's query to null. + // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`. + url.search = ''; + } + + // 7. Return url. + return url; +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy} + */ +export const ReferrerPolicy = new Set([ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]); + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy} + */ +export const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'; + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies} + * @param {string} referrerPolicy + * @returns {string} referrerPolicy + */ +export function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + + return referrerPolicy; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +export function isOriginPotentiallyTrustworthy(url) { + // 1. If origin is an opaque origin, return "Not Trustworthy". + // Not applicable + + // 2. Assert: origin is a tuple origin. + // Not for implementations + + // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy". + if (/^(http|ws)s:$/.test(url.protocol)) { + return true; + } + + // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy". + const hostIp = url.host.replace(/(^\[)|(]$)/g, ''); + const hostIPVersion = isIP(hostIp); + + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + + // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy". + // We are returning FALSE here because we cannot ensure conformance to + // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost) + if (url.host === 'localhost' || url.host.endsWith('.localhost')) { + return false; + } + + // 6. If origin's scheme component is file, return "Potentially Trustworthy". + if (url.protocol === 'file:') { + return true; + } + + // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy". + // Not supported + + // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy". + // Not supported + + // 9. Return "Not Trustworthy". + return false; +} + +/** + * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?} + * @param {external:URL} url + * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" + */ +export function isUrlPotentiallyTrustworthy(url) { + // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy". + if (/^about:(blank|srcdoc)$/.test(url)) { + return true; + } + + // 2. If url's scheme is "data", return "Potentially Trustworthy". + if (url.protocol === 'data:') { + return true; + } + + // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were + // created. Therefore, blobs created in a trustworthy origin will themselves be potentially + // trustworthy. + if (/^(blob|filesystem):$/.test(url.protocol)) { + return true; + } + + // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin. + return isOriginPotentiallyTrustworthy(url); +} + +/** + * Modifies the referrerURL to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerURLCallback + * @param {external:URL} referrerURL + * @returns {external:URL} modified referrerURL + */ + +/** + * Modifies the referrerOrigin to enforce any extra security policy considerations. + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 + * @callback module:utils/referrer~referrerOriginCallback + * @param {external:URL} referrerOrigin + * @returns {external:URL} modified referrerOrigin + */ + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer} + * @param {Request} request + * @param {object} o + * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback + * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback + * @returns {external:URL} Request's referrer + */ +export function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) { + // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for + // these cases: + // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm. + // > Note: If request's referrer policy is the empty string, Fetch will not call into this + // > algorithm. + if (request.referrer === 'no-referrer' || request.referrerPolicy === '') { + return null; + } + + // 1. Let policy be request's associated referrer policy. + const policy = request.referrerPolicy; + + // 2. Let environment be request's client. + // not applicable to node.js + + // 3. Switch on request's referrer: + if (request.referrer === 'about:client') { + return 'no-referrer'; + } + + // "a URL": Let referrerSource be request's referrer. + const referrerSource = request.referrer; + + // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer. + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the + // origin-only flag set to true. + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + + // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set + // referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary + // policy considerations in the interests of minimizing data leakage. For example, the user + // agent could strip the URL down to an origin, modify its host, replace it with an empty + // string, etc. + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + + // 8.Execute the statements corresponding to the value of policy: + const currentURL = new URL(request.url); + + switch (policy) { + case 'no-referrer': + return 'no-referrer'; + + case 'origin': + return referrerOrigin; + + case 'unsafe-url': + return referrerURL; + + case 'strict-origin': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerOrigin. + return referrerOrigin.toString(); + + case 'strict-origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 3. Return referrerOrigin. + return referrerOrigin; + + case 'same-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // 2. Return no referrer. + return 'no-referrer'; + + case 'origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request's current URL are the same, then + // return referrerURL. + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + + // Return referrerOrigin. + return referrerOrigin; + + case 'no-referrer-when-downgrade': + // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a + // potentially trustworthy URL, then return no referrer. + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return 'no-referrer'; + } + + // 2. Return referrerURL. + return referrerURL; + + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} + +/** + * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header} + * @param {Headers} headers Response headers + * @returns {string} policy + */ +export function parseReferrerPolicyFromHeader(headers) { + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` + // and response’s header list. + const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/); + + // 2. Let policy be the empty string. + let policy = ''; + + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty + // string, then set policy to token. + // Note: This algorithm loops over multiple policy values to allow deployment of new policy + // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values. + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + + // 4. Return policy. + return policy; +} diff --git a/node_modules/pathfinding/.npmignore b/node_modules/pathfinding/.npmignore new file mode 100644 index 0000000..f28d261 --- /dev/null +++ b/node_modules/pathfinding/.npmignore @@ -0,0 +1,5 @@ +*.swp +node_modules/ +/lib +site/ +release/ \ No newline at end of file diff --git a/node_modules/pathfinding/.travis.yml b/node_modules/pathfinding/.travis.yml new file mode 100644 index 0000000..10a7a00 --- /dev/null +++ b/node_modules/pathfinding/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.11" + - "0.10" +before_script: + - npm install -g gulp + - npm install -g mocha +sudo: false diff --git a/node_modules/pathfinding/README.md b/node_modules/pathfinding/README.md new file mode 100644 index 0000000..45a390c --- /dev/null +++ b/node_modules/pathfinding/README.md @@ -0,0 +1,264 @@ +PathFinding.js +============== +#### A comprehensive path-finding library in javascript. #### + +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/qiao/PathFinding.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![Build Status](https://travis-ci.org/qiao/PathFinding.js.svg?branch=master)](https://travis-ci.org/qiao/PathFinding.js) +[![Dependency Status](https://david-dm.org/qiao/pathfinding.js.png)](https://david-dm.org/qiao/pathfinding.js) +[![Documentation Status](https://readthedocs.org/projects/pathfindingjs/badge/)](https://readthedocs.org/projects/pathfindingjs/?badge=latest) + +Introduction +------------ + +The aim of this project is to provide a path-finding library that can be easily incorporated into web games. It may run on Node.js or the browser. + +It comes along with an [online demo](http://qiao.github.com/PathFinding.js/visual) to show how the algorithms execute. (The pathfinding speed is slowed down in the demo) + +Note that this project only provides path-finding algorithms for 2D space. If you need to work in a 3D environment, then you may use [@schteppe](https://github.com/schteppe)'s [fork](https://github.com/schteppe/PathFinding3D.js). + +There is new documentation being written for PathFinding.js. You can read it [here](http://pathfindingjs.readthedocs.org/en/latest/). Note that this is in very early stages and far from complete so keep your eyes open for mistakes and don't hesitate to open a pull request in case you find one. + +Server +------ + +If you want to use it in Node.js, you may install it via `npm`. + +```bash +npm install pathfinding +``` + +Then, in your program: + +```javascript +var PF = require('pathfinding'); +``` + +See the `Basic Usage` section below for usage details. + + +Browser +------- + +If you have bower installed then you can install it with the following command: + +```bash +bower install pathfinding +``` + +By default bower will install pathfinding under the bower_components folder, so to include it in your page do something like: + +```html + +``` + +You can also grab a release from the [Releases Page](https://github.com/imor/pathfinding-bower/releases) if you don't use bower. + +Basic Usage +----------- + +To build a grid-map of width 5 and height 3: + +```javascript +var grid = new PF.Grid(5, 3); +``` + +By default, all the nodes in the grid will be able to be walked through. +To set whether a node at a given coordinate is walkable or not, use the `setWalkableAt` method. + +For example, to set the node at (0, 1) to be un-walkable, where 0 is the x coordinate (from left to right), and +1 is the y coordinate (from up to down): + +```javascript +grid.setWalkableAt(0, 1, false); +``` + +You may also pass in a matrix while instantiating the `PF.Grid` class. +It will initiate all the nodes in the grid with the same walkability indicated by the matrix. +0 for walkable while 1 for blocked. + +```javascript +var matrix = [ + [0, 0, 0, 1, 0], + [1, 0, 0, 0, 1], + [0, 0, 1, 0, 0], +]; +var grid = new PF.Grid(matrix); +``` + +Currently there are 10 path-finders bundled in this library, namely: + +* `AStarFinder` * +* `BestFirstFinder` +* `BreadthFirstFinder` * +* `DijkstraFinder` * +* `IDAStarFinder.js` * +* `JumpPointFinder` * +* `OrthogonalJumpPointFinder` * +* `BiAStarFinder` +* `BiBestFirstFinder` +* `BiBreadthFirstFinder` * +* `BiDijkstraFinder` * + +The prefix `Bi` for the last four finders in the above list stands for the bi-directional searching strategy. + +Also, Note that only the finders with trailing asterisks are guaranteed to find the shortest path. + +To build a path-finder, say, the `AStarFinder`: + +```javascript +var finder = new PF.AStarFinder(); +``` + +To find a path from (1, 2) to (4, 2), (Note: both the start point and end point should be walkable): + +```javascript +var path = finder.findPath(1, 2, 4, 2, grid); +``` + +`path` will be an array of coordinates including both the start and end positions. + +For the `matrix` defined previously, the `path` will be: + +```javascript +[ [ 1, 2 ], [ 1, 1 ], [ 2, 1 ], [ 3, 1 ], [ 3, 2 ], [ 4, 2 ] ] +``` + +Be aware that `grid` will be modified in each path-finding, and will not be usable afterwards. If you want to use a single grid multiple times, create a clone for it before calling `findPath`. + +```javascript +var gridBackup = grid.clone(); +``` + + +Advanced Usage +-------------- + +When instantiating path-finders, you may pass in additional parameters to indicate which specific strategies to use. + +For all path-finders, you may indicate whether diagonal movement is allowed. The default value is `false`, which means that the path can only go orthogonally. + +In order to enable diagonal movement: + +```javascript +var finder = new PF.AStarFinder({ + allowDiagonal: true +}); +``` + +When diagonal movement is enabled, you might want to prevent the path from touching the corners of the occupied grid blocks. This is usually desirable if the objects using the path have physical width and can also move between the grid cells. + +To enable the corner crossing prevention: + +```javascript +var finder = new PF.AStarFinder({ + allowDiagonal: true, + dontCrossCorners: true +}); +``` + +Note that `dontCrossCorners` only makes sense when `allowDiagonal` is also used. Currently all algorithms except `JumpPointFinder` support this feature. + +For `AStarFinder`, `BestFirstFinder` and all their `Bi` relatives, you may indicate which heuristic function to use. + +The predefined heuristics are `PF.Heuristic.manhattan`(defalut), `PF.Heuristic.chebyshev`, `PF.Heuristic.euclidean` and `PF.Heuristic.octile`. + +To use the chebyshev heuristic: + +```javascript +var finder = new PF.AStarFinder({ + heuristic: PF.Heuristic.chebyshev +}); +``` + +To build a `BestFirstFinder` with diagonal movement allowed and a custom heuristic function: + +```javascript +var finder = new PF.BestFirstFinder({ + allowDiagonal: true, + heuristic: function(dx, dy) { + return Math.min(dx, dy); + } +}); +``` + +To smoothen the path, you may use `PF.Util.smoothenPath`. This routine will return +a new path with the original one unmodified. + +```javascript +var newPath = PF.Util.smoothenPath(grid, path); +``` + +Note that the new path will be compressed as well, i.e. if the original path is +`[[0, 1], [0, 2], [0, 3], [0, 4]]`, then the new path will be `[[0, 1], [0, 4]]`. + +To just compress a path without smoothing it, you may use `PF.Util.compressPath`. + +```javascript +var newPath = PF.Util.compressPath(path); +``` + +To expand the compressed path like `[[0, 1], [0, 4]]` back to `[[0, 1], [0, 2], [0, 3], [0, 4]]`, +you may use `PF.Util.expandPath`. + +```javascript +var newPath = PF.Util.expandPath(path); +``` + + +Development +------------ + +Layout: + + . + |-- lib # browser distribution + |-- src # source code (algorithms only) + |-- test # test scripts + |-- utils # build scripts + |-- benchmark # benchmarks + `-- visual # visualization + +Make sure you have `node.js` installed, then use `npm` to install the dependencies: + + npm install -d + +The build system uses gulp, so make sure you have it installed: + + npm install -d -g gulp + +To build the browser distribution: + + gulp compile + +To run the tests +(algorithms only, not including the visualization) with +[mocha](http://mochajs.org/) and [should.js](https://github.com/visionmedia/should.js) +First install mocha: + + npm install -d -g mocha + +Then run the tests: + + gulp test + +To run the benchmarks: + + gulp bench + +Or if you are feeling lazy, the default gulp task does everything(except running the benchmarks): + + gulp + +License +------- + +[MIT License](http://www.opensource.org/licenses/mit-license.php) + +© 2011-2012 Xueqiao Xu <xueqiaoxu@gmail.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/node_modules/pathfinding/TODO b/node_modules/pathfinding/TODO new file mode 100644 index 0000000..170848e --- /dev/null +++ b/node_modules/pathfinding/TODO @@ -0,0 +1,4 @@ +implement IDS +implement Dynamic Weighting +customize heuristic functions on demo page +beautify play panel diff --git a/node_modules/pathfinding/benchmark/benchmark.js b/node_modules/pathfinding/benchmark/benchmark.js new file mode 100644 index 0000000..ee9d2d6 --- /dev/null +++ b/node_modules/pathfinding/benchmark/benchmark.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node + +var colors = require('colors'); +var PF = require('..'); +var parseMap = require('./parse_map').parse; +var parseScen = require('./parse_scen').parse; +var testCases = require('./test_cases'); +var path = require('path'); + +function profile(callback) { + var startTime = Date.now(); + ret = callback(); + var endTime = Date.now(); + return { + returnValue: ret, + time: endTime - startTime + }; +} + +/** + * @param {object} opt + * @param {string} opt.header + * @param {string} opt.footer + * @param {PF.*Finder} opt.finder + * @param {PF.Grid} opt.grid + * @param {number} opt.startX + * @param {number} opt.startY + * @param {number} opt.endX + * @param {number} opt.endY + */ +function benchmark(opt) { + var result = profile(function() { + return opt.finder.findPath( + opt.startX, + opt.startY, + opt.endX, + opt.endY, + opt.grid + ); + }); + var fields = [ + opt.header, + (''+result.time + 'ms').yellow, + 'length' , formatFloat(PF.Util.pathLength(result.returnValue)), + opt.footer, + ]; + console.log(fields.join(' ')); +} + +function formatFloat(float) { + return Math.round(float * 1000) / 1000; +} + +function map2grid(map) { + return new PF.Grid(map.width, map.height, map.grid); +} + +testCases.forEach(function(test) { + var grid = map2grid(parseMap(path.join(__dirname, test.map))); + var scens = parseScen(path.join(__dirname, test.scen)).scenarios; + var select = test.select; + + select.forEach(function(id) { + var scen = scens[id]; + var result = benchmark({ + header: 'AStarFinder', + finder: new PF.AStarFinder({allowDiagonal: true}), + grid: grid, + startX: scen.startX, + startY: scen.startY, + endX: scen.endX, + endY: scen.endY, + footer: '(optimal: '.grey + (''+scen.length).green + ')'.grey + }); + }); +}); diff --git a/node_modules/pathfinding/benchmark/map/64room_000.map b/node_modules/pathfinding/benchmark/map/64room_000.map new file mode 100644 index 0000000..25ddf71 --- /dev/null +++ b/node_modules/pathfinding/benchmark/map/64room_000.map @@ -0,0 +1,516 @@ +type octile +height 512 +width 512 +map +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@ +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................................................................................@...............................................................................................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................................................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +................................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@ +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +................................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................................................................................... +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +................................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................................................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@...............................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................................................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@...............................................................@...............................................................................................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@............................................................................................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +................................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................................................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................................................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................................................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +................................................................@...............................................................@...............................................................@...............................................................@...............................................................................................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@...............................................................@............................................................... +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.@@@@@@@@@@@@@@@@@@ +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................................................................................@............................................................... +@...............................................................................................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +................................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................................................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... +@...............................................................@...............................................................@...............................................................@...............................................................@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@...............................................................@...............................................................@............................................................... diff --git a/node_modules/pathfinding/benchmark/map/arena.map b/node_modules/pathfinding/benchmark/map/arena.map new file mode 100644 index 0000000..c204a01 --- /dev/null +++ b/node_modules/pathfinding/benchmark/map/arena.map @@ -0,0 +1,53 @@ +type octile +height 49 +width 49 +map +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +TTT............TTTT.TTT...TTTT.TTTT............TT +TT.............TTT........TTT..TTT.............TT +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T.......................TT......................T +T......................TTT......................T +T......................TTT......................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +TTT............TTTT............TTTT............TT +TTT............TTTT............TTTT............TT +TTT............TTTT............TTTT............TT +TT.............TTT.............TTT.............TT +TT..............................................T +TT..............................................T +TT..............................................T +TT..............................................T +T...............................................T +T...............................................T +T...............................................T +TT..............................................T +TTT.............................................T +TTT.............................................T +TTT.............................................T +T...............................................T +TTT............TTTT............TTTT............TT +TTT............TTTT............TTTT............TT +TTT............TTTT............TTTT............TT +TT.............TTT.............TTT.............TT +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...............................................T +T...................TTT...TTT...................T +TTT............TTTT.TTTT..TTTT.TTTT............TT +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT diff --git a/node_modules/pathfinding/benchmark/map/lak304d.map b/node_modules/pathfinding/benchmark/map/lak304d.map new file mode 100644 index 0000000..e566f21 --- /dev/null +++ b/node_modules/pathfinding/benchmark/map/lak304d.map @@ -0,0 +1,198 @@ +type octile +height 194 +width 193 +map +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTT..........TTTT..TTTTTTT@@@@@@@@@@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@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT........TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT.TT.TTTTTTTTTTTTTTTTTTTTTT........TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT......TTTTTTTTTTTTTTTTTTTTTT.....TT.TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT...................................TT.TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T.....................................TT.TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT........................................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTT....................TTTTT...............TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTT.......TT..........TTTTTTTT............TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT.....TTTT.TT....TT.TTTTTT..............TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT.TTTTTTT.....TTTTTTTT...TTTTTTTTTT.............TTTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTTTT.TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT....TTTTTTTT...TTTTTT.....TTTTTTTTT..............TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTTT....T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT.......TT@TTTT..TTTTTTT....TT.TT..................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT........T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT.....TTTTTT@TTTT..TTTT@T...........................TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@TT...........T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTT....TTTTTTT@TTTT...TTTTTT...........................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT............TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT...TT....TTTT..TT@TTT...TTTTTTT..........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@TT...............T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT...........TTTT..TT@TTTTT..TTTTTT..........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TT....TT............T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT...................TT@TTTT..TTTTTTT.........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT....TTTT............T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT....................TTT@TTTT..TTTTTT.........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TT...TTTTTT............TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT......................TT@TTTT..TTTTTTT........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT...TTTTTT.............TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTT...........TTTT.......TTTTTT....TTTTTT........................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@TT....TTTTTT.............TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@TT..TT...........TTTT......TTTTTTTT....TTTTTT.......................TTT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT....TTTTTT.............TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@TT...............TTTT......TTTTTTTTTT..TTTT@TT.......................TT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT.......TT...............TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@TTTT..............TTTT.....TTTTTT@TTTT...TTTTTT.......................TT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TT.........................TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@T.T.................TT....TTTTTTTT@TTTT..TTTT@TT......................TT@TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT........................TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@T.......................TTTT.....TTT@TTT...TTTTTT......................TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TT........................TTTT....TT@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@..............TTT......TTTT.......TT@TTTT..TTTTTTT............TTTT..TT.TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@TTT......................TTTTT......T@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@TTT..........TTTTT.....TTTT.........TT@TTT...TTTTTT............TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@TT......................TTTTT........T@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@TTTT.........TTTTT@TTTTTT............TT@TTTT...TTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@TT@TT....TT.................TTT..........T@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@TTTT.........TTTTTTTTTT...............TT@TTTT..TTTTTTTT........TTTTTTTTTTTTTTTT@@@@TTTTTTTT@@@@@@@@@@@@@@@@@TTTTTT.TTTTTT...............TT........TT...T@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@TTTTT.........TTTTTTTTTT....TT......TT.TTTTTTT...TT@TTTT.......TTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTT@@@@@@@@@@@@@TT@TT..TTTTTTT.............TT........TTT...T@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@TT.............TTTTTTT.....TTTT....TTTTTT@TTTT..TT@TTTTTT.....TTTTTTTTTTTTTTTT..TTTTTTT@@@@TTTTTTT@@@@@@@@@TT@TTT...TTTTTT..........TTTT........TTTTT...T@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@TTTT............TTT@TTT.....TTTTT...TTTTTTTT@TTT.TTTTTTTTTTT....TTTTTTT...............TTTTTTT@@@TTTTTTTT@@@@TTT@TT...TTTTTTT.........TTTTT......T.TTTTTT...T@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@TTTTT.............TTTTT......TTTTT...TTTTT.TT@TTTTTTTTTTTTTTT....TTTT.....................TTTTTTT@@@@TTTTTTTTTT@TTT...TTTTT..........TTTTTT....TTTT.TTTTT...T@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@TTTTT..............TTTT........TT.....TTT...TTTTTTTTTTTTTTTTTT................................TTTTTTT@@@@TTTTTTTTT......TT..........TTTTTT.....TTTT.TTTTT....T@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@T.TTT..............TTTTT.....................TTTTTTTTTTTTTTTTT.....................................TTTTTTT@TTTTTTT...................TTTTT...TT.TTTT..TTT.....T@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@....T........T.....TTTT......................TTTTTTTTTTTTT............................................TTTTTTTTTTTT....................TTT...TTTT..T............T@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@T....T.....TTTTT....TTTT.....................TTTTTTTTTTT...................................................TTTTTTTTT.........................TTTT.............TTT@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@...........TTTTT............................TTTTTTTTT.......................................................TTTTTTTT.........................TTT..............TTTT@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@T............TTTT...........................TTT@TTTTTT.......................................................TTTTTTTT...................................TT......TTTT@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@TTT...........TTT......................TTTT.TTT@TTTTT........................................................TT@TTTTTTT.................................TTT......TTTT@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@TTTT...................................TTTTTTT@TTT...........................................................TT@TTTT..TTTT..............................TTTT......TTTT@@@@@@@@@@@@@ +@@@@@@@@@@@@@TTTTT.....................TT...........TTTTTTT@TTT...........................................................TT@TTTTT....TTT.........................TT..TTT.......TTTT@@@@@@@@@@@@@ +@@@@@@@@@@@@@TTTTTT..................TTTTT..........TTTTTT@TTT...........................................................TTTTTTTT...TTTTT........................TTTT...........TTTTT@@@@@@@@@@@@ +@@@@@@@@@@@@TTTTTTT.....TTT...........TTTT............TTT@TTT..........................................TTT...............TT@TTTTT...TTTTTTT......................TTTT..........TTTTTT@@@@@@@@@@@@ +@@@@@@@@@@@@TTTTTT..T...TTT...........TTTT...........TTT@TTT...................................TTTT....TTT..............TT@TTTTT....TTTT.TTTT....................TTT........TTTTTTTTTT@@@@@@@@@@@ +@@@@@@@@@@@T.TT....TTT.TTT............TTT...........TTT@TTT...................................TTTTTT...TT.......TT......TT@TTTT......TTT...TTTT............................TTTTTTTTTTTT@@@@@@@@@@ +@@@@@@@@@@T........TTT.TTT...TTT...................TTT@TTT...................................TTTTTTTTT.TT.......TT.....TT@TTTTT............TTTTTT.........................TTTT.....TTTT@@@@@@@@@@ +@@@@@@@@@@............TTT....TTT...............TTTTTT@TTT.................................TTTTTTT@TTTTTTTT.....TTT.....TT@TTTT.............TTTTTT.....................TT.TTTT........TTT@@@@@@@@@ +@@@@@@@@@T...........TTT....TTT....T...........TTTTT@TTT..............................TTTTTTTTTTTTTT@TTTTTT....TTT....TT@TTTTT..............TTTT....................T.TTTT.T..........TT@@@@@@@@@ +@@@@@@@@@TT..........TTT....TTT...TTT..........TTTTTTTT...........................TTTTTTTTTTTTTTTTTTT@@@TTT..TTTT....TTTTTTTT................TT...................TTTTTTT.............TTT@@@@@@@@ +@@@@@@@@TTTT........TTT....TTT....TTT..........TTTTTTT...................TTTTTTTTTTTTTTTTTTTT@TTTTTTT@@TTT..TTTTTTTTTTTTTTTTT.....................................TTTTT................TTT@@@@@@@ +@@@@@@@@TTTTT.......TTT....TTT...TTT...TT.....TTT@TTT...................TTTTTTTTTTTTTTTTT@@@@@@TTTTTT@@TTT..TTT@TTTTTTTTTTTT......................................TTTTT................TTT@@@@@@@ +@@@@@@@TTTTT.........T....TTT...TTT....TTT...TTT@TTT....................TTTTTTTTTTTTT@@TT@@@@@@TTTTTT@@TTT..TTT@@T@@TTTTTTTT.......................................TTT...........TTTT.....T@@@@@@ +@@@@@@T.T................TTT....TTT...TTT...TTT@TTT.....................TTTTTTTTT@@TT@@TT@TT@@@TTTTTT@TTTT..TTT@@TTTTTTTTTTT.......................................T.............TTTT....TT@@@@@@ +@@@@@@...........TTT.....TTT...TTT....TTT..TTT@TTT.....................TTTTTTTTTT@@TT@@TT@TT@TTTTTTTT@TTT..TTT@@TTTTTTTTTTTTT.......................T.........................TTTTTTTT...TTT@@@@@ +@@@@@T..........TTTTT.....T....TTT...TTT@TTTT@TTT.....................TTTTTTTTTTT@@TTTTTT@TTTTTTTTTTT@TTT..TTT@@TTTTTTTTTTTTTT.....................TTTTTT.T...................TTTTTT@TT...TT@@@@@ +@@@@@...........TTTTT.........TTT....TTTTTTTTTTT.....................TTTTTTTTTTTTTTT@TTTTTTTT@TT@TTTT@TTT..TTT@TTTTTTTTTTTTTTTT..................TTTTTTTTTT...................TTTTTTTT....TTT@@@@ +@@@@T............TTTT.........TTT...TTTTTTTTTTT.....................TTTTTT@@@TT@@TTTT@TTTTTTTT@TTTT@@@TT..TTTT@TTTTTT...TTTTTTTT.................TTTTTTTTTTT..................TTTTTTTTT....TTT@@@ +@@@T.............T.................TTT.TTTTTTT.....................TTTTTT@@@TTTT@TTTTTT@TTTT@TT@TTT@@@@@@@TTT@@TTTTTT....TTTTTTTT................TTTTTTTTT....................TTTTTTT......TTT@@@ +@@@T...............................TTT.TTTTTTT....................TTTTTT@@TTTTTT@TTTTTTTTTTTTTTTTTTT@@@@@@@@@@TTTTTTT.....TTTTTTTT...............TTTTTTTTT....................TTTTTTT.......TTT@@ +@@TT......................TTTT.....TT..TTTTTTT...................TTTTTT@@TTTTTTTTTTTTTTTTTTTTTTT@TTTTTTT@@@@@@@TTTTTT......TTTTTTTT................TTTTTTT...................................TT@@ +@@TTT.....................TTTTT.........TTTTTT..................TTTTTT@@TTTTTTTTT.TTTTTTTTTTTTTT@@@TTTTTTTT@@@TTT...........TTTTTTTT...............TTTTTT.....................................TT@ +@TTTT.....................TTTTT........TTTTT...................TTTTTT@@@TTTTTTTTT.TTTT..TTTTTTTTTTTTTTTTTTTTTTTTT............TTTTTTTT..............TTTT......................................TTTT +TT.........................TTTT........TTTTT..................TTTTTT@@@@TTTTTTT.........TTTTT..TTTTT@@TTT.TTTTTTT.............TTTTTTTT.............TTTT......................................TTTT +TT.....................................TTTTT.................TTTTTT@TT@TTTTTTTTTT........T.....T@T.TTTT@T...TTTT...............TTTTTTTT.............TT......................................TTTTT +TTT..................T...............TTTTTT.............TTTTTTTTTT@TTTTTTTTTTTTTTTTT...........T@T...TTTT...TTTT................TTTTTTT................................................TT.TTTTTTT +TTT..........TTTTTT.TT.............TTTTTTTT.............TTTTTTTTT@TTTTTTTTTTTTTTTTTTT..........T@T...T@T....TT...................TTTTTTT..............................................TTTTT..TTTT +TTT..........TTTTTTTTTT.............TTTTTTT............TTTTTTTTT@TTTTTTTTTTTTTTTTTTTTT.........TTT...T@T...TT.....................TTTTTTT.....................................TTTTTTTTTTT.....TTT +TT...........TTTT@TTTTTT............TTTTTTT.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............T@T...T......................TTTTTTT..................................TTTTTTTTTT...........T +T.............TTTTTTTTT.............TTTTTT..............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............TTT.TTTTT....................TTTTTTT..................TTTT............TTTTTTTT.............T +T..............TTTTTTTT...............TTTT...............TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TT.TTTTTT...................TTTTTTT..................TTTT............TTTTTTT..............T +T..............TTTTTTTT................TTT...............TTTTTT@TTTTT.TTTTTTTTTTTTTTT....................TTTTTT....................TTTTT...................TTTT.............TTTT................T +T..............TTTT...T..................................TTTTT@@TTTT..TTTTTTTTT.........................TT.TTT......................TTTTT..................TTTT.................................T +T...............TTT......................................TTTTTTTTTTT...TTTTTTT..........................T...........................TTTTT...................TTT.................................T +T................TT......................................TTTTTTTTT.....................................TT...........................TTTTT....................T..................................T +T................T..................TT..................TTTTTTTTTT...................................TTT............................TTTTT....................T..................................T +TT...............T.................TTTTT................TTTTTTTTT...................................TTTTT...........................TTTT.....................T..................................T +TTT.......TTT....T....TTT........TTTTTTT................TTTTTTTTT...................................TTTTT............................TT....................TTTT.................................T +TTTT.....TTTTT..TTT..TTTTT......TTTTTTTT................TTTTTTTTT...................................TTTT..................................................TTTTT.................................T +TTTT.....TTTTT..TTT..TTTTT.....TTTTTTTTT...............TTTTTTTTTT...................................TTTT..................................................TTTTTT..........TT..........TT........T +TTT.......TTTT..TTT..TTTTT......TTTTTTT................TTTT.TTTTT..............................T..........................................................TTTTT.........TTTTTT........TTTTT.....T +TT.........TT....T....TTT........TTTTTT................TTTT...................................TTT.......................................TT....................T.........TTTTTT.......TTTTTT.....T +T......TT........T........TTT.....TTTTT................TTTTTTT................................TTT.....................................TTTTTT..................T.........TTTTTT.......TTTTTT.....T +T.....TTTT.......T........TTTT....TTTTT...............TTTTTTTT.........................TTTT...........................................TTTTTT..................T.........TTTTTT.......TTTTTT.....T +T....TTTTTT......T.......TTTTT...TTTTT................TTTTTTTT.........................TTTT............................................TTTTT..................TT........TTTTTT.......TTTT.......T +T.....TTTT......TT........TTTT...TTTTT................TTTTTTTT......TTTTTTTTT........TTTTTT............................................TTTTT.................TTTT.........TT...........TT.......T +TTTT...TT......TTTT........TT....TTTTT...............TTTTTTTT.......TTTTTTT.....TT..TTTTTTT.............................................TTTTT................TTTT............................TTTT +TTTT...........TTTT.............TTTTT...............TTTTTTTTT..........TTT.....TTTTTTTTTTT..............................................TTTTTTTTTT......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTTTTTTT@T.........TTTTT.TTTTTTT.............................................TTT.....TTTTTTTTTTT....TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +TTTT@@@@@@@@@@@TTTT@@@@@@@@@@@@TTTTTTT.............TTTTTTTTTTTTTTTTTTTTTTTTTTT.TTTT.............................................TTTT...TTTTTTTTTTTT....TTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT +TTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT.............TTTTTTTTT...TTT....TTTTT....TTTT............................................TTTTT.TTTTTTTTTTTTTT....TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTTTTTTTT..TTTT....TTTT.....TTTT.............................................TTTTTTTTTTTTTTTTTTT....TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..............TTTTT.....TTTT......................................................TT.TT.TTTTT@@@@@TTTTTT..............TTTTTTTTTTTTTTTTTT.T.TTT.TTTTTTTTTTTT +TTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT...............TTTTT....TTTT.....................................................TTTTTTTT@TT@@@@@@@TTTT...............TTTTTTTT.......TTT...TTT...TTTTTT...T +T@TTT...T....TTTTTTTTTT@@TTTTTTTTTT@TT...............TTTTT.............................................................TTTTTT@@@@@@@@@@@@TTT................TTTTTTTT.......TT...................T +TTTT...........TTT..TTTTTT....TTTTTT@TT..............TTTTT.............................................................TTTT@@@@@@@@@@@@@TTTT...............TTTTT.......TTT.TT...................T +TTTTTT.........T@T..TTTTTTTT....TTTT@TT..............TTTTT.............................................................TTTT@@@@@@@@@@@@@TTTT...............TTTTT.......TTTTTT...................T +TTTTTT.........T@T....TTTTTT....TTTT@TT...............TTTT.........................................................TT..T@@@@@@@@@@@@@@@@TTTT...............TTTTT.......TTTTTT...................T +TTTT...........TT.....TTTT......TTTT@TT...............TT..........................................................TTTTTT@@@@@@@@@@@@@@@@TTT...............TTTTT........TTTTTT...................T +TTTT...........T......TTTT......TTTTT@TT..........................................................................TTTTT@@@@@@@@@@@@@@@@TTTT...............TTTTT........TTTTTT...................T +TTTT...........TT.....TTTT.......TTTT@TT..........................................................................TTTT@@@@@@@@@@@@@@@@@TTTT...............TTTTT............T.......TTTT.........T +TTTTT..........TT.....TTTTT......TTTT@TT...........................................................................TTTT@@@@@@@@@@@@@@@@TTTT...............TTTTT....................TTTTTTT......T +TTTTT.........TTT.....TTTTT......TTTTTTT.................TT.........................................................TT@@@@@@@@@@@@@@@@TTTT................TTTT.....................TTTTTTT......T +TTT............T......TTT.......TTTTTT@TT..............TTTTT.......................................................TT@@@@@@@@@@@@@@@@@TTTT...............TTTTT.....................TTTTTTT......T +TTT............T......TTT.......TTTTTT@TT..............TTTTTT......................................................T@@@@@@@@@@@@@@@@@@TTTT..................T.........................TTTT..TTTTT +T..............T................TTTTTT@TT...............TTTTT....................................................TTT@@@@@@@@@@@@@@@@@@TTTT..................................TTTT....TTTTTTT.TTTTT +T..............T................TTTTTTT@T...............TTTTT..................................................TTTTT@@@@@@@@@@@@@@@@@TTTT...................................TTTTTTT.TTTTTTT.TTTTT +T.............TTT.................TTTTT@TT...............TTTTT.................................................TTTTT@@@@@@@@@@@@@@@@TTTTT..................................TTTTTTTTTTTTTTT..TTTTT +T.............TTTT.................TTTT@TT...............TTTTTT................................................TTTT@@@@@@@@@@@@@@@@TTTTTT...............TTT................TTTTTTTTTTTTTTT..TTTTT +T.............TTTT.................TTTT@TT...............TTTTTTT...............................................TTTT@@@@@@@@@@@@@@@TTTTTTT..............TTTTT...............TTTTTTTTTTTTTTT.....TT +TT............TTTT..................TTTT@TT..............TTTTTTT................................................TTT@@@@@@@@@@@@@@@TTTTTTT..............TTTTT...............TTTTTTTTTTTTTTT......T +TTT...........TTTT..................TTTT@TT............TTTTTTTTT................................................TTT@@@@@@@@@@@@@@@TTTTTTTTT............TTTTTTT............TTTTTTTTTTTTTTTT....TTT +TTT.................................TTTT@TT...........TTTTTTTTTT.....................T............................T@@@@@@@@@@@@@@@TTTTTTTTT............TTTTTTTT.............TTTTTTTTTTTTT.....TTT +TT..................................TTTT@TT............TTTTTTTTTT....................TT...........................T@@@@@@@@@@@@@@@TTTTTTTTT...........TTTTTTTTT.................TTTTTTTTT.....TTT +TT...................................TTTT@TT...........TTTTTTTTTTT..................TTT...........................TT@@@@@@@@@@@@@TTTTTTTTT............TTTTTTTT..T.................TTTTTTT.......T +TT...................................TTTT@TT............T.....TTTTT.................TTT......TT...................TTT@@@@@@@@@@@TTTTT.................TTTTTTTT.TTT...............TTTTT........TTT +@T.T.................................TTTT@TT...................TTTTT............TTTTTTT......TT.................TTTTT@@@@@@@@@@TTTTT..................TTTTTTTT.TT................TTTTT.......TTTT +@TTTT................................TTTTTTT....................TTTTT...........TTTTTT......TTT.................TTTTT@@@@@@@@@TTTTT..................TTTTTTTT..................TTTTTT........TTTT +@@TT..................................TTTTTTTT...................TTTTT..........TTTTTT......TTT.................TTTTT@@@@@@@@TTTTT..................TTTTTTTTTT................TTTTTTTT.......TTT@ +@@TT....................T.............TTTTTTTT....................TTTTT........TTTTTTT......TTT.................TTT.T@@@@@@@TTTTT..................TTTTTTTTTTTTT..............TTTTTTTT........T@@ +@@@T..................TTTT............TTTTTTTTT....................TTTTT.......TTTTTTT......TTTTTT..................TT@@@@@TTTTT...................TTTTTTTTTTTTTTT.............TTTTTTT.......TT@@ +@@@T.TTT.............TTTTTT...........TTTTTTTTT.....................TTTTT......TTTTTT......TTTTTTT..................TTT@@@TTTTT....................TTTTTTTTTTTTTTT.................TT........T@@@ +@@@@TTTT..TT.........TTTTTT..........TTTTTTTTTT......................TTTTT.....TTTT@T......TTTTTT...................TTT@@TTTTT....................TTTTTTTTTTTT@TTT...........................T@@@ +@@@@@TTTT.TT.........TTTTTTT.........TTTTTTTTTTT......................TTTTTTTTTTTTT@T......TTTTTT...................TTTTTTTTT....................TTTTTTTTTT@TTTTT...........................T@@@@ +@@@@@TTTT.TT..........TTTTTT.........TTTTTTTTTTTT......................TTTTTTTTTTTTT......TTTTTTT..................TTTTTTTTT....................TTTTTTTTTTTT@@TTTT..........................@@@@@ +@@@@@@@TTTT...........TTTTTTT.........TT..TTTTTTTT......................TTTTTTTTTT@T......T@TTTTT.................TTTTTTTTT....................TTTTTTT....TTTT@@TTTT..TTT................TTT@@@@@ +@@@@@@TTTT@T...........TTTTTT.............TTTTTTTTT.....................TTTTTTTTTT@.......T@TTTT.................TTTTTTTTT....................TTTTTTT.......TTTT@TTTTTTTTTT..............TT@@@@@@ +@@@@@@@TTTTTTTTT........TTTTTT.............TTTTTTTTT....................TTTTTTTTTT@.......TTTTTT.............TTTTTTTTTTTTT...................TTTTTTT.........TTTTT@TTTTTTTTT..........TTTTT@@@@@@ +@@@@@@@TTTTTTTTT........TTTTTTT.............TTTTTTTTT...................TTTTTTTTTTTTT@.....TTTTT.........TTTTTTTTTTTTTTTT...................TTTTTTT............TTTT@@TTTTTTT..........TTTT@@@@@@@ +@@@@@@@@TTTTTTTT.........TTTTTT..............TTTTTTTT..................TTTTTTTTTTTTTTTTTT@@TTTTTTTTT.TTTTTTTTTTTTTTTTTTT....................TTTTTTTT.............TTTT@@TTTTT.........TTTTT@@@@@@@ +@@@@@@@@@TTTTTTT.........TTTTTTT..............TTTTTTT.................TTTTTT......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................TTTTTTTT..............TTTTT@TTTT.........TTTT@@@@@@@@ +@@@@@@@@@TTTTTT...........TTTTTT...............TTTTT..................TTTTTT.........TTTTTTTTTTTTTTTTTTTTTTT.................................TTTTTTT................TTTT@@TTTT.......TTT@@@@@@@@@ +@@@@@@@@@@TTTTT...........TTTTTTT.....................................TTTTT..............TTTTTTTTTTTTTTTT.......................................TTT...................TTTT@@TTTT....TT@T@@@@@@@@@ +@@@@@@@@@@TTTTT............TTTTTTT.....................TTT..............TT...................TTTTTTTT..................................TT...............................TTTT@@TTT...TTT@@@@@@@@@@ +@@@@@@@@@@@TTTT.............TTTTTT....................TTTTT...................................TTTTTT..................................TTTT...............................TTTTT@TTTTTTTT@@@@@@@@@@ +@@@@@@@@@@@@TTTT............TTTTTTT...................TTTTTT...................................TTTT..................................TTTTTT................................TTTT@@TTTTT@@@@@@@@@@@ +@@@@@@@@@@@@TTTTT............TTTTTT...................TTTTTTT......TT..........................TTTT.................................TTTTTTT.................................TTTTTTTTT@@@@@@@@@@@@ +@@@@@@@@@@@@@TTTT............TTTTTTT.................TTTTTTTTT....TTTTT........................TTTT................................TTTTTTTT.................................TTTTTTTTT@@@@@@@@@@@@ +@@@@@@@@@@@@@TTTTT............TTTTTT.................TTTTTTTTTT...TTTTT...........................................................TTTTTTTTTT.....................TTT.......TTTTTTTTT@@@@@@@@@@@@@ +@@@@@@@@@@@@@@TTTT.............TTT....................TTTTTTTTTT.TTTTTT..........................................................TTTTTTTTTTT....................TTTT.....TTTTTTTTTTT@@@@@@@@@@@@@ +@@@@@@@@@@@@@@TTTTTTTTTT.......T..........................TTTTTTTTTTTT........................................................TTTTTTTTT.TTT....................TTTT......TTTTTTTTTT@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@TTTTTTTTT...................................TTTTTTTTTTT.......................................................TTTTTTTTT........................TTTTTT.......TTTTTTTT@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@TTTTTTTT.........................TTT........TTTTTTTTT.......................................................TTTTTTTTT........................TTTTTTT........TTTTTT@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@TTTTTTTT........................TTTTT........TTTTTTTTTTTT................................................TTTTTTTTTTT........................TTTTTTTT..........TTT@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@TTTTTT.........................TTTTTTT.....TTTTTTTTTTTTTTTTT........................................TTTTTTTTTTTTTTT.......................TTTT@TTTT.........TTTT@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@TTTTTT........................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTT...................................TTTTTTT@@@TTTTTTT........................TTT@TTTTT........TTTT@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@TTTTT..........................TTTTTT...T@TTTTTTTTTTTTTTTTTTTT..............................TTTTTTT@@@@TTTTTTTTTT......................TTTTTTTTTTT........TTTT@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@TTT..................T..........TTTTT....TTTT@TTTTTTTTTTTTTTTT....TTTT..................TTTTTTT@@@@TTTTTTTT...........................TTTTTTTTTT.........TTTT@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@T..................TTT...........TT...T.TTTT@TT..TTTTTTTTTTT....TTTTTTTTT...........TTTTTTT@@@TTTTTTTTTT..............................TTTT@TT..........TTTTT@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@..................TTTT................TTTT@TT.....TTTT...T.....TTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTT..TTTT..............................TTTTT............TTTT@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@T................TTTTTTTT...........TTTTTT@TT..................TTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTTT....TTT...............................TTTTT..........TTTT@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@.................TTTTTT..T........T@TTTT@TT....................TTTTTTTTTTTTTTTTT@TTTTTTTT..TTTTT.......................................TTTT.........TTTT@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@T.................TTTTTTT@T........TTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTT...TTTT..........................TTT...........TTTTT.....TTTTTT@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@T..................TT@TTTTTTT...T.TTTT@TTTT.....................TTT@@@TTTTTTTTTT...TTTT....TT.........................TTTTT...........TTTTTT....TTTTTT@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@T.................TTTT@@TTT@@T.T@TTTT@TTTTT.....................TTTTTTTTTTTTTT.....TTTT..............................TTTTTTT..........TTTTTTT...TTTTT@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@TT...............TTTTTT@TTTT...TTTTT@TTTT......................TTTTTTTTTTTTT......................................TTTTTTTTT............TTTTTT..TTTTT@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@TTT.............TTTTTTT@@@TTTTTTTT@TTTTT........................TTTTTTTT@TT....................................TTTTTTTTT..............TTTTTTT.TTTT@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@TTTT............TTTTTTTTT@@@TTTTTT@TTTT................................T@TT..................................TTTTTTTTTTT..............TTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@TT.............TTTTTTTTT@@@TTTTT@TTTT.................................T@TT.................................TTTTTTTTTTTT...............TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@TT.TT..............TTTTT@@TTTTT@TTTTT.................................T@TT...............................TTTTTTTTTTT@TT................TT.TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTT..............TTTT@T@TTTT@TTTT..................................T@TT.............................TTTTTTTTTTTTTT.....................TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT...............TTT.T@TTTT@TTTTTTT................................T@TT............................TTTTTTTTTTTTTTT................TT...TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT...TTTT...........T@TTTT@TTTTTTT................................T@TT............................TTTTTTTTTTTTTTT..............TTTT..TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T..TTTT..........T@TTTT@TT@TTTTTTT.......................TTTTTTTT@TT............................TTTTTTTTTTTTTTT.............TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT........TTTTTT@TTTTTTTTTT.......................TTTTTTTT@TT.............................TTTTTTTTTTTTT.......TTT....TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT...T@TTTT@TTTTTTTTTT........................TTTTTTTT@TT...............................TTTTTTTT.TTT....TTTTTT...TTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@TTTTTTT..TTTT@TTTTTTTTTTTTT...........T.........TTTTTTTTT@TT...............................TTTTTT...TTTT..TTTTTTT....T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@TTT.TTTT@TTTTTTTTTTTT..........TTT.........TTTTTTTTT@TT................................TTTT.....TTT.TTTTTTTTT.TT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@@@@@@TTTT@TTTTTTTTT@TTT........TTTTTT........TTTTTTTTT@TT................TTTT............TT.......TTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TT@@@TTTTT@TTTTTTTTTTT...........TTTTT........TTTTTTTTT@TT...............TTTTT......................TTT@TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T@TTTTTTTTTT@TTTTTTT...........TTTTT........TTTTTTTTT@TT...........TTTTTTTTTT..................TTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTT...........TTTT.........TTTTTTTTT@TT........TTTTTTTTTTTTT..................TTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT............T...........TTTTTTTTT@TT......TTTTTTTTT..TTTT..................TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT.............TT...........TTTTTTTTT@TT......TTT..TTTT...TTT.T...............TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTT.............T............TTTTTTTTT@TT...........TTT....TTTTTTT.............TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTT..............T............TTTTTTTTT@TT............TT.....TTTTTT.........T...TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT...............TT............TTTTTTTTT@TTTTTT...............TTTTT........TTT...TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT.............TTT....................T@TTTTTT.........TTTT..TTTT.......TTTTTT..T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT............TT....................T@TTTTTT.......TTTTTTT..TTT.......TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT....TTT..TT.....................T@TTTTTT........TTTTTT..TTT.TT.....TTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTT..TTTT..T......................T@TTTTTT.......TTTTTTT..TTT.TTTTT..TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT.TTT...T......................T@TTTTTT.......TTTTTTT...TTTTTTTT..T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@T.TTTTTTT.......TTTTT...TT...TTT@TTTTTT........TTTTTTT..TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT......TTTTT........TTTTTTTTT...TTTTT..TTTTTT..TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT......TTTTTTTTT....TTTTTTTTTTTTTTTTT..TTTT@@TTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT....TTTTTTTTT....TTTTTTTTTTTTTTTTT......TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ diff --git a/node_modules/pathfinding/benchmark/map/losttemple.map b/node_modules/pathfinding/benchmark/map/losttemple.map new file mode 100644 index 0000000..7003392 --- /dev/null +++ b/node_modules/pathfinding/benchmark/map/losttemple.map @@ -0,0 +1,516 @@ +type octile +height 512 +width 512 +map +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@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TTTTTTTTTTTTTTTTTTTTT@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTT...WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTT...WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTT...WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....................................................TTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....................................................TTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................@@@@TTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@...@...TTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@...@...TTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@@@@@@@...@...TTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTT...TTTTTT...TTTT..................................................@............@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTT...TTTTTT...TTTT..................................................@............@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTT...TTTTTT...TTTT..................................................@............@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTT...TTTTTT...TTTT................................................@@@.........@@@@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT......................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT......................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT......................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT..................................................................................................................@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT..................................................................................................................@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....TTTTTTTTT.......................................................................................................@@@........@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@.........................................................................................................................@........@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSS@................................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@.........................................................................................................................@........@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSS@................................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@.........................................................................................................................@@@@@@@..@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSS@@@@@............................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@...............................................................................................................................@..@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSS@.........................................WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@...............................................................................................................................@..@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSS@.........................................WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@...............................................................................................................................@..@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSS@.........................................WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..@...............................................................................................................................@@@@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSS@@@@.........................................WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT............................................................................................................................@.............................................TTTTTTTTTTTTTTTTTTTTTTWWWWSSSSSSSSSSSSSSSS...................................TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT............................................................................................................................@.............................................TTTTTTTTTTTTTTTTTTTTTTWWWWSSSSSSSSSSSSSSSS...................................TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT@@@@........................................................................................................................@.............................................TTTTTTTTTTTTTTTTTTTTTTWWWWSSSSSSSSSSSSSSSS...................@@@@@@@@@.......TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@........................................................................................................................@.......................................TTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWSSSSSSSSSSSSS......................SSSSS@.......TTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@........................................................................................................................@.......................................TTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWSSSSSSSSSSSSS......................SSSSS@.......TTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@@@@.....................................................................................................................@.......................................TTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWSSSSSSSSSSSSS......................SSSSS@.......TTTTTT...@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@......................................................TTTTTTTTTTTTT..................................................@...................................TTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...SSSSS@....TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@......................................................TTTTTTTTTTTTT..................................................@...................................TTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...SSSSS@....TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........@@@@@@@@@@@@@@.........................................TTTTTTTTTTTTT..................................................@...................................TTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...SSSSS@@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................@.........................................TTTTTTTTTTTTTTTTTTT.......TTTTTTTTTTTTT......................TTT.......................................TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................@.........................................TTTTTTTTTTTTTTTTTTT.......TTTTTTTTTTTTT......................TTT.......................................TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................@.........................................TTTTTTTTTTTTTTTTTTT.......TTTTTTTTTTTTT......................TTT.......................................TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTT....TTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............@.............................................WWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTT....TTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............@.............................................WWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTT....TTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............@.............................................WWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTT....TTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............@.............................................WWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTT.............................TTTTTT......@............@......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........TTT..........................................@@@WWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTT.............................TTTTTT......@............@......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........TTT..........................................@@@WWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTT.............................TTTTTT......@@@@...@@@@@@@......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........TTT..........................................@@@WWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTT..................................................@..@................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......@...................................@@@@@@WWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTT..................................................@..@................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......@...................................@@@@@@WWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTT..................................................@@@@@@@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@...................................@@@@@@WWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWW@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTT.....................................................@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWW@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTT.....................................................@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWW@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTT.....................................................@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTT...........................................................@............................@.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSSSSSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTT...........................................................@............................@.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSSSSSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTT...........................................................@@@@@...................@@@@@@.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................@@@WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSSSSSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@...............................................................@...................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...................................TTT..........WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSS@SSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWSSSWWWSSSSTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@...................................................................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...................................TTT..........WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSS@SSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWSSSWWWSSSSTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@...................................................................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...................................TTT..........WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSS@SSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWSSSWWWSSSSTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@...................................................................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...................................TTT..........WWWWWWWWWWWWWWWWWWWWWWSSSSSSSSS@SSS.......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWSSSWWWSSSSTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@WWWW@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW................................................................................................................TTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT...@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@..........................SSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWWTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@WWWW@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW................................................................................................................TTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT...@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@..........................SSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWWTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@WWWW@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW................................................................................................................TTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT...@@@WWWWWWWWWWWWWWWWSSSSSS@@@@@@@@@@..........................SSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWWTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW...TTTTTTTTTT.............................................................................TTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT......@@@@@@WWWWWWWWWWSSSSS@....................................SSSSSSSSSSSSSSSSSSSWWW@@@WWWTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW...TTTTTTTTTT.............................................................................TTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT......@@@@@@WWWWWWWWWWSSSSS@....................................SSSSSSSSSSSSSSSSSSSWWW@@@WWWTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW...TTTTTTTTTT.............................................................................TTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTT......@@@@@@WWWWWWWWWW@@@@@@....................................SSSSSSSSSSSSSSSS@@@WWW@@@WWWTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWW@@@@@@WWWTTTTTTTTTT@@@TTTTTTTTTTTTTTTTWWWWWWWTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTT.............@@@@@@.............................................SS@SSSWWWSSS@............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWW@@@@@@WWWTTTTTTTTTT@@@TTTTTTTTTTTTTTTTWWWWWWWTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTT.............@@@@@@.............................................SS@SSSWWWSSS@............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWWWW@@@@@@WWWTTTTTTTTTT@@@TTTTTTTTTTTTTTTTWWWWWWWTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTT.............@@@@@@.............................................SS@SSSWWWSSS@............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@TTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT.......................................................SSSWWWWWWWWWW.........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@TTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT.......................................................SSSWWWWWWWWWW.........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@TTTTTTTTT..........................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT................................................@@@@...@@@WWWWWWWWWW.........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTT......................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@SSSSS@...WWW..........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTT......................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@SSSSS@...WWW..........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTT......................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@SSSSS@...WWW..........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTT......................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@@@@@@@...WWW..........TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW....................................................................................TTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW....................................................................................TTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW....................................................................................TTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................TTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................TTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................TTTTTT....................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................................................................TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................................................................TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..........................................................................................................................................TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......................................................................................................................................TTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......................................................................................................................................TTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......................................................................................................................................TTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......@@@...................................................................................................................................................TTTTTT....................................................TTTTTTTTTTTT.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......@@@...................................................................................................................................................TTTTTT....................................................TTTTTTTTTTTT.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......@@@...................................................................................................................................................TTTTTT....................................................TTTTTTTTTTTT.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.......@@@...................................................................................................................................................TTTTTT....................................................TTTTTTTTTTTT.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@WWWWWWWWWWWWWWWWWWW.........................................................................................................................................................................................................................TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@WWWWWWWWWWWWWWWWWWW.........................................................................................................................................................................................................................TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@WWWWWWWWWWWWWWWWWWW.........................................................................................................................................................................................................................TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT...................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT...................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT...................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT............................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTT......................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT............................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTT......................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTT............................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTT......................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@TTTTTTTTTT................................................................TTT.......................TTT...................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@TTTTTTTTTT................................................................TTT.......................TTT...................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@TTTTTTTTTT................................................................TTT.......................TTT...................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT@@@@TTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................TTT.......................TTT.............................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT@@@@TTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................TTT.......................TTT.............................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT@@@@TTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................TTT.......................TTT.............................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTT@@@@TTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................TTT.......................TTT.............................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@TTTTTTTTTTTTTTTT...................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@TTTTTTTTTTTTTTTT...................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@TTTTTTTTTTTTTTTT...................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..................................................................@...TTT.......................TTT.....@.............................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..................................................................@...TTT.......................TTT.....@.............................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...TTT.......................TTT.....@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................@...................................TTT.......................TTT.....................................@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................@...................................TTT.......................TTT.....................................@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................@...................................TTT.......................TTT.....................................@................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTT...TTTT........@...................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTT...TTTT........@...................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.........................................@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTT...TTTT........@...................................................TTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTT...TTT.......................................................................................TTT.....@.......................................................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTT...TTT.......................................................................................TTT.....@.......................................................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTT...TTT.......................................................................................TTT.....@.......................................................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTT...TTT.......................................................................................TTT.....@.......................................................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT.........................................................TTTTTTTTTTTTTTTT...TTTT...TTT......................................TTTTTTT...TTT.............................................................................................TTT@@@..........................................................TTT...TTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT.........................................................TTTTTTTTTTTTTTTT...TTTT...TTT......................................TTTTTTT...TTT.............................................................................................TTT@@@..........................................................TTT...TTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT.........................................................TTTTTTTTTTTTTTTT...TTTT...TTT......................................TTTTTTT...TTT.............................................................................................TTT@@@..........................................................TTT...TTTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................................TTTTTTT......................................................TTTTTTTTTT......................................................................................................@@@@@@@................................................................TTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................................TTTTTTT......................................................TTTTTTTTTT......................................................................................................@@@@@@@................................................................TTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................................TTTTTTT......................................................TTTTTTTTTT......................................................................................................@@@@@@@.........................................................@@@@@@@TTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................TTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@.....................................................@............@..........................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................TTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@.....................................................@............@..........................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................TTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@...................................................@@@..........@@@..........................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT.......................................................................................................................TTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@...................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT.......................................................................................................................TTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@...................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT.......................................................................................................................TTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@...................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@TTTTTTTTTTTTTTTTTTT....................................................................................................................TTTTTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@@@@................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@TTTTTTTTTTTTTTTTTTT....................................................................................................................TTTTTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@@@@................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@TTTTTTTTTTTTTTTTTTT....................................................................................................................TTTTTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@@@@................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@TTTTTTTTTTTTTTTTTTT....................................................................................................................TTTTTTTTTTTTTTTTTTT...TTT..........................................................................................TTT...@@@@@@@@@@@@@@@@................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTT.............................TTT.......................TTT......................................@@@@@@@@@@@@@@@@@@@..........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTT.............................TTT.......................TTT......................................@@@@@@@@@@@@@@@@@@@..........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTT.............................TTT.......................TTT......................................@@@@@@@@@@@@@@@@@@@..........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTT......@...TTT.............................TTT.......................TTT................................TTT..@.......@@@@@@@@@@@@@@@@.........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTT......@...TTT.............................TTT.......................TTT................................TTT..@.......@@@@@@@@@@@@@@@@.........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTT....@@@...TTT.............................TTT.......................TTT................................TTT@@@.......@@@@@@@@@@@@@@@@.........................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTT.............................................................................................................................................TTT.............................TTT.......................TTT...................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTT.............................................................................................................................................TTT.............................TTT.......................TTT...................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@TTTTTTTTTTTTTTTTTTT...................................@@@@@@@@@@@@@.............................................................................................TTT.............................TTT.......................TTT...................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT.....................................@............@.............................................................................................TTT.............................TTT..........................TTT.............................TTT@@.................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT.....................................@............@.............................................................................................TTT.............................TTT..........................TTT.............................TTT@@.................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT...................................@@@............@@@@@@@@@@@...................................................................................TTT.............................TTT..........................TTT.............................TTT@@.................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT..................................@.........................@...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...................................TTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT..................................@.........................@...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...................................TTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT..................................@.........................@...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...................................TTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTT@@@@@@TTTTTTTTTTTTT................................@@@.........................@@@@@@@.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...................................TTTTTTTTTT......................TTTTTTTTTTTTTTTTTTTTTTTTTT......................................@@@..........@@@..........................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@..@.....@.........................@..@..................................@...............................................................................................................................................................................................................................................@............@.............................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@..@.....@.........................@..@..................................@...............................................................................................................................................................................................................................................@............@.............................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@..@@@@@@@.........................@@@@..................................@@@@............................................................................................................................................................................................................................................@@@@@@@@@@@@@@.............................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@.....@...............................@.....................................@...............................................................................................................................................................................................................................................@.......................................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@.....@...............................@.....................................@...............................................................................................................................................................................................................................................@.......................................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@.....@...............................@.....................................@@@@@@@@........................................................................................................................................................................................................................................@.......................................................................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT..@...............................@............................................@.........................................................................................................................................................................................................................................TTTTTTTTTTTTT.............................................................TTTTTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT..@...............................@............................................@.........................................................................................................................................................................................................................................TTTTTTTTTTTTT.............................................................TTTTTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT..@.............................@@@............................................@@@@......................................................................................................................................................................................................................................TTTTTTTTTTTTT.............................................................TTTTTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..@............................@..................................................@......................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..@............................@..................................................@......................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..@@@@.........................@..................................................@......................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT.....@..@...................@..@..................................................@..........................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT.....@..@...................@..@..................................................@..........................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT.....@..@...................@..@..................................................@..........................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT.....@@@@...................@@@@..................................................@..........................................................................................................................................................................................................................................TTTTTTTTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT................................................................TTTTTT.........@................................................................................................................................................................................................................................TTTTTT.......TTTTTTTTTTTTTTTTTTTTTT..................@...................@......TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT................................................................TTTTTT.........@................................................................................................................................................................................................................................TTTTTT.......TTTTTTTTTTTTTTTTTTTTTT..................@...................@......TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT................................................................TTTTTT.........@@@@.............................................................................................................................................................................................................................TTTTTT.......TTTTTTTTTTTTTTTTTTTTTT................@@@...................@@@@...TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTT........@...................................................................................................................................................................TTTT......................................................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTT...............@..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTT........@...................................................................................................................................................................TTTT......................................................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTT...............@..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTT........@...................................................................................................................................................................TTTT......................................................TTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTT...............@..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTT.....@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...TTT..........................TTTTTTTTTTTTT......................TTT.......TTTTTTTTTTTTTTTT......................................TTTTTTTTTT......TTTTTTTTTTTTTTTTTTT...............@.............................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTT.....@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...TTT..........................TTTTTTTTTTTTT......................TTT.......TTTTTTTTTTTTTTTT......................................TTTTTTTTTT......TTTTTTTTTTTTTTTTTTT...............@.............................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTT.....@.............................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................TTTTTTTTTT...TTT..........................TTTTTTTTTTTTT......................TTT.......TTTTTTTTTTTTTTTT......................................TTTTTTTTTT......TTTTTTTTTTTTTTTTTTT.............@@@.............................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTTTTT..@.............................................................TTT..........................................................................................TTTTT.......@.........................................................TTTTTTTTTT..................@...............@..@............................@...TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTTTTT..@.............................................................TTT..........................................................................................TTTTT.......@.........................................................TTTTTTTTTT..................@...............@..@............................@...TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTTTTT..@.......................................................@@@...TTT..........................................................................................TTTTT....@@@@.........................................................TTTTTTTTTT..................@@@@@@@@@@@@@@@@@..@@@@....................@@@@@@...TTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT..@.........................................................@...TTT.............................TTT.......................TTT................................TTTTTT.......@@@@@@@@@@@@@@@@@@@......................................TTTTTTTTTTTTTTTT..................................@.............................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT..@.........................................................@...TTT.............................TTT.......................TTT................................TTTTTT.......@@@@@@@@@@@@@@@@@@@......................................TTTTTTTTTTTTTTTT................................................................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT..@.........................................................@...TTT.............................TTT.......................TTT................................TTTTTT.......@@@@@@@@@@@@@@@@@@@......................................TTTTTTTTTTTTTTTT................................................................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTT@@@.........................................................@...TTT.............................TTT.......................TTT................................TTTTTT.......@@@@@@@@@@@@@@@@@@@......................................TTTTTTTTTTTTTTTT................................................................TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTT......................................@@@@@@@@@@@@@@@@@@@@@@@...TTT.............................TTT.......................TTT................................TTTTTTTTT@@@@@@@@@@@@@@@@@@@@................................................TTTTTT.............................................................TTT...TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTT......................................@@@@@@@@@@@@@@@@@@@@@@@...TTT.............................TTT.......................TTT................................TTTTTTTTT@@@@@@@@@@@@@@@@@@@@................................................TTTTTT.............................................................TTT...TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTT......................................@@@@@@@@@@@@@@@@@@@@@@@...TTT.............................TTT.......................TTT................................TTTTTTTTT@@@@@@@@@@@@@@@@@@@@................................................TTTTTT.............................................................TTT...TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTT..........................................@@@@@@@@@@@@TTTT@@@...TTT.............................TTT.......................TTT................................TTTTTT@@@@@@@@@@@@@@@@@@@.......................................................................................................................TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTT..........................................@@@@@@@@@@@@TTTT@@@...TTT.............................TTT.......................TTT................................TTTTTT@@@@@@@@@@@@@@@@@@@.......................................................................................................................TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTT..........................................@@@@@@@@@@@@TTTT@@@...TTT.............................TTT.......................TTT................................TTTTTT@@@@@@@@@@@@@@@@@@@.......................................................................................................................TTT......@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@@@@TTT.............................................................................................TTTTTT@@@@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@@@@TTT.............................................................................................TTTTTT@@@@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@@@@TTT.............................................................................................TTTTTT@@@@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@................TTT.............................................................................TTTTTT@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@................TTT.............................................................................TTTTTT@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................@@@@@@@@@@@@@................TTT.............................................................................TTTTTT@@@@@@@@@@@@@..........................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................@@@@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@@@@.............................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................@@@@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@@@@.............................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................@@@@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@@@@.............................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................@@@@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@@@@.............................................................................................................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@............................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@............................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTT...................................................@@@@@@@...TTT..........................................................................................TTTTTT@@@@@@@............................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTT..........................................................@@@...TTT.............................................................................................TTT@@@.......................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTT..........................................................@@@...TTT.............................................................................................TTT@@@.......................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTT@@@.......................................................@@@...TTT.............................................................................................TTT@@@.......................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTT.....@.........................................................@......TTTTTTT......TTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTTTTTTTTT........@..........................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTT.....@.........................................................@......TTTTTTT......TTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTTTTTTTTT........@..........................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................TTTTTTTTTT.....@@@@......................................................@...@@@TTTTTTT...@@@TTTTTTTTTTTTTTTT.............................TTTTTTTTTTTTTTTT...TTTTTTTTTT........@..........................................................................................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................................@...........@......................................................@..@..@.........@...TTTTTTTTTTTTT@@@@............................@@@@@@............@..@...............@.............................................................................................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT............................................................@...........@......................................................@..@..@.........@...TTTTTTTTTTTTT@@@@............................@@@@@@............@..@...............@.............................................................................................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........................................................@@@@.........@@@......................................................@@@@..@@@@@@@@@@@...TTTTTTTTTTTTT.....................................@@@@.......@@@..@@@@@@@@@@@@@@..@.............................................................................................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT........@......@..................@..@..........................................................TTT...TTT.......................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT........@......@..................@..@..........................................................TTT...TTT.......................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT........@......@..................@..@..........................................................TTT...TTT.......................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT........@@@@@@@@..................@@@@..........................................................TTT...TTT.......................................................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTT................TTT.......................TTT......................................................................................TTTTTTT...TTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTT................TTT.......................TTT......................................................................................TTTTTTT...TTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTT................TTT.......................TTT......................................................................................TTTTTTT...TTTTTTTTTTTTTTTTTTT................................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTT................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTT................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................................TTT.......................TTT...................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTT................................................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................................................................TTT.......................TTT.........................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................................................................TTT.......................TTT.........................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..........................................................................................................................................................................TTT.......................TTT.........................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTT...TTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT..........................................................................................................................................................................TTT.......................TTT...................................................................................WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT..........................................................................................................................................................................TTT.......................TTT...................................................................................WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT.............................................................................@@@..........................................................................................TTT.......................TTT...................................................................................WWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT...............................................................................@..........................................................................................TTT.......................TTT................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT...............................................................................@..........................................................................................TTT.......................TTT................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT...............................................................................@..........................................................................................TTT.......................TTT................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT................................................................@@@@.........@@@..........................................................................................TTT.......................TTT................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT......................................................................@........@..........................................................................................................................................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT......................................................................@........@..........................................................................................................................................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT......................................................................@...@@@@@@..........................................................................................................................................................................................................@@@WWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................................................................@..@................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................................................................@..@................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT................................................................@@@@@@@@@@................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..................................................................@.......................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..................................................................@.......................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..................................................................@.......................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....................TTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTT.........................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTT.........................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT..........................................................TTTTTTTTTTTTTTTT.........................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................TTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.......................TTTTTTTTTTTT..........TTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...TTT.......................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...TTT.......................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTT...TTT.......................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........TTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTT................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........TTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTT................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTT.........TTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTT................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT.............................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT.............................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTT.............................................................................................................................................................................................................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......TTTTTTTTT................................................TTTTTTT............................................................................................@.....................@......TTTTTTTTTT......................................@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......TTTTTTTTT................................................TTTTTTT............................................................................................@.....................@......TTTTTTTTTT......................................@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......TTTTTTTTT................................................TTTTTTT............................................................................................@.....................@......TTTTTTTTTT......................................@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT....@@@TTTTTTTTT................................................TTTTTTT.........................................................................................@@@@.....................@@@@...TTTTTTTTTT......................................@@@@WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...TTT...................................................TTTTTTTTTTTTT.....................................................................................@............................@...TTTTTTTTTTTTT.............................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...TTT...................................................TTTTTTTTTTTTT.....................................................................................@............................@...TTTTTTTTTTTTT.............................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...TTT...................................................TTTTTTTTTTTTT.....................................................................................@............................@...TTTTTTTTTTTTT.............................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT................................................TTTTTTTTTTTTTTTT................................................................TTT...............@.............................TTTTTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT................................................TTTTTTTTTTTTTTTT................................................................TTT...............@.............................TTTTTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT................................................TTTTTTTTTTTTTTTT................................................................TTT.......@@@.....@.............................TTTTTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...................................................TTTTTTTTTTTTTTTTTTTTTT..........................................................TTTTTT.........@..@.....@................................TTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...................................................TTTTTTTTTTTTTTTTTTTTTT..........................................................TTTTTT.........@..@.....@................................TTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@...................................................TTTTTTTTTTTTTTTTTTTTTT..........................................................TTTTTT.......@@@..@@@@@@@@@@@............................TTTTTTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSS@................................................TTTTTTTTTTTT....................................................................TTTTTTTTTTTT...@...............@..@.....................@.......TTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSS@................................................TTTTTTTTTTTT....................................................................TTTTTTTTTTTT...@...............@..@.....................@.......TTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSS@@@@.............................................TTTTTTTTTTTT....................................................@@@@@@@@@.......TTTTTTTTTTTT...@...............@@@@.....................@@@@....TTTTTTTTT................................TTT....WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@TTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...SSSSSSSSSSSS@................................................WWW@@@TTTWWWW@@@............................................@.........TTTTTTTTTTTTTTTTTTT...@...TTTTTTTTT................................TTTTTTTTTTTTTTTT....................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@TTTTTTTTTWWWWWWW@@@@@@TTT@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...SSSSSSSSSSSS@................................................WWW@@@TTTWWWW@@@............................................@.........TTTTTTTTTTTTTTTTTTT...@...TTTTTTTTT................................TTTTTTTTTTTTTTTT....................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@TTTTTTTTTWWWWWWW@@@@@@TTT@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...SSSSSSSSSSSS@................................................WWW@@@TTTWWWW@@@............................................@.........TTTTTTTTTTTTTTTTTTT...@...TTTTTTTTT................................TTTTTTTTTTTTTTTT....................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@TTTTTTTTTWWWWWWW@@@@@@TTT@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...SSSSSSSSSSSS@@@@......................................@@@@@@@WWW@@@TTTWWWW@@@.........................................@@@@.........TTTTTTTTTTTTTTTTTTT@@@@...TTTTTTTTT................................TTTTTTTTTTTTTTTT....................................WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTT@@@@@@@@@@TTTTTTTTTWWWWWWW@@@@@@TTT@@@@@@@@@@TTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSS@.....................................@SSSSSSSWWWWWW@@@@@@@WWWWWW.....................................@................TTTTTTTTTT..........TTTTTTTTTTTT................................TTTTTTTTTTTTT................................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSS@.....................................@SSSSSSSWWWWWW@@@@@@@WWWWWW.....................................@................TTTTTTTTTT..........TTTTTTTTTTTT................................TTTTTTTTTTTTT................................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSS@@@@@@@@@@@.........................@@@SSSSSSSWWWWWW@@@@@@@WWWWWW.....................................@................TTTTTTTTTT..........TTTTTTTTTTTT................................TTTTTTTTTTTTT................................TTT.......WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS@..@..................@..@SSSSSSSWWWWWWWWWWWWWWWWWWWWWW.....................................@.............................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTT.............................TTTTTTT...WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS@..@..................@..@SSSSSSSWWWWWWWWWWWWWWWWWWWWWW.....................................@.............................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTT.............................TTTTTTT...WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS@@@@..................@@@@SSSSSSSWWWWWWWWWWWWWWWWWWWWWW...................................@@@.............................TTTTTTTTTTTTTTTTTTTTTTTTTT.............................TTTTTTTTTTTT.............................TTTTTTT...WWWWWWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWW@@@..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTT.........................TTTTTTT...WWWWWWWWWWWWWWWW@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWW@@@..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTT.........................TTTTTTT...WWWWWWWWWWWWWWWW@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTT......SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWWWWW@@@..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTT.........................TTTTTTT...WWWWWWWWWWWWWWWW@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW@@@.....................................@................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT...................TTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW@@@.....................................@................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT...................TTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW@@@.....................................@@@@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTT...................TTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@WWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW........................................@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@WWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW........................................@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@WWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW........................................@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTT@@@@@@WWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWWWWWW......................................@@@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTT..........TTTTTTTTTTTTT...@@@WWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@@@@.....................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@@@@.....................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@@@@.....................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@TTTTTT..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@TTTTTT..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWWWW@@@@TTTTTT..................................@...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTT@@@TTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@...................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@TTTTTTTTT...............................@..........................TTTTTTTTTTTTTTTTTTTTTT...................................................TTTT......TTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSSSSSSSS@...................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@TTTTTTTTT...............................@..........................TTTTTTTTTTTTTTTTTTTTTT...................................................TTTT......TTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWWWWWSSSSSSSSS@@@@@@@...................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWW@@@@@@@TTTTTTTTT...............................@@@@.......................TTTTTTTTTTTTTTTTTTTTTT...................................................TTTT......TTTTTTTTTTTTTTTTTTTTTTTTTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWSSSSSSSSSSSS@................................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWW@@@@@@TTTTTTTTTTTTT.....................................@.......................TTTTTT...TTTTTTT......................................................TTTTTTT......TTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@TTT@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWSSSSSSSSSSSS@................................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWW@@@@@@TTTTTTTTTTTTT.....................................@.......................TTTTTT...TTTTTTT......................................................TTTTTTT......TTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@TTT@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWWWWWWWWSSSS@@@@@@@@@................................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSWWWWWWW@@@@@@TTTTTTTTTTTTT.....................................@.......................TTTTTT...TTTTTTT......................................................TTTTTTT......TTTTTTTTTTTTTTTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@TTT@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@TTTT........@................................SSSSSSSSSSSSSSSSSSSSSSSWWWSSSSSSSSSWWWWTTTTTTTTTTTTTTTTTTTTTTTTT..................................@..........................................................................................TTTTTTTTTTTTT......TTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@TTTT........@................................SSSSSSSSSSSSSSSSSSSSSSSWWWSSSSSSSSSWWWWTTTTTTTTTTTTTTTTTTTTTTTTT..................................@..........................................................................................TTTTTTTTTTTTT......TTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@TTTT........@................................SSSSSSSSSSSSSSSSSSSSSSSWWWSSSSSSSSSWWWWTTTTTTTTTTTTTTTTTTTTTTTTT..................................@..........................................................................................TTTTTTTTTTTTT......TTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWW@@@@@@@@@TTTT........@................................SSSSSSSSSSSSSSSSSSSSSSSWWWSSSSSSSSSWWWWTTTTTTTTTTTTTTTTTTTTTTTTT..................................@..........................................................................................TTTTTTTTTTTTT......TTTTTTTTTT@@@WWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@WWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..@..................................@SSSSSSSSSSSSSSSSWWWWWWWWWWSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.....................................@.......................................................................................TTTTTTTTTTTTTTTT......TTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..@..................................@SSSSSSSSSSSSSSSSWWWWWWWWWWSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.....................................@.......................................................................................TTTTTTTTTTTTTTTT......TTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT..@..................................@@@@@SSSSSSSSSSSSWWWWWWWWWWSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.....................................@.......................................................................................TTTTTTTTTTTTTTTT......TTTTTTT@@@WWWWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@WWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT..@..@...................................@SSSSSSTTTTTTTTTTWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................@.......................................................................................TTTTTTTTTTTTTTTTTTT...TTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT..@..@...................................@SSSSSSTTTTTTTTTTWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................@.......................................................................................TTTTTTTTTTTTTTTTTTT...TTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT..@@@@...................................@@@@@@@TTTTTTTTTTWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................@@@@@...................................................................................TTTTTTTTTTTTTTTTTTT...TTTTTTTTTTWWWWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@...@.........................................................................................TTTTTTTTTTTTT..........TTTTTTWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@...@.........................................................................................TTTTTTTTTTTTT..........TTTTTTWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@...@@@@@@@...................................................................................TTTTTTTTTTTTT..........TTTTTTWWWWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@WWWWWWWTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.....................................@.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@.........@......................................................................................TTTTTTTTTTTTTTTT.......TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.....................................@.......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...............................................@.........@......................................................................................TTTTTTTTTTTTTTTT.......TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTT.....................................@@@@....TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................................@@@@@@.......@@@......................................................................................TTTTTTTTTTTTTTTT.......TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................TTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................TTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................TTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................................................................TTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......TTTWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......TTTWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT......TTTWWWWWWWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT......................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTT@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTT@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTT................................................................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTTTTT@@@WWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTT......TTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTT......TTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT...................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................................................................................TTTTTTTTTTTTTTTTTTT......TTTTTTTTTTTTT@@@WWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT.............TTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT.............TTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT.............TTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTT.............................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................................................................TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTT.............TTTWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................................................................................TTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................................................................@@@..........................TTTTTTTTTTTTTTTTTTTTTTTTTTTT.......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.....................................................................@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......TTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.....................................................................@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......TTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT..........................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......................................................@@@..........@@@.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT......TTT@@@WWWW@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................................@.........@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................................@.........@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT......................................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT........................................................@.......@@@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT..........................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWW@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT.......................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTTTTTTTTTTTT........@......@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT.......................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTTTTTTTTTTTT........@......@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTT.......................TTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT............................TTTTTTTTTTTTTTTTTTTT........@......@......TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...................TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTTWWWWWWWWWW@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TTTTTTTTTTTTTTTTTTTTTT.............TTTTTTTTTTTTTTTT...TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.............TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT...TTTTTT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@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ diff --git a/node_modules/pathfinding/benchmark/parse_map.js b/node_modules/pathfinding/benchmark/parse_map.js new file mode 100644 index 0000000..598272c --- /dev/null +++ b/node_modules/pathfinding/benchmark/parse_map.js @@ -0,0 +1,79 @@ +#!/usr/bin/env node + +/** + * Convert the `map` files into json + * + * All maps begin with the lines: + * + * type octile + * height x + * width y + * map + * + * where x and y are the repsective height and width of the map. + * + * The map data is store as an ASCII grid. The following characters are possible: + * + * . - passable terrain + * G - passable terrain + * @ - out of bounds + * O - out of bounds + * T - trees (unpassable) + * S - swamp (passable from regular terrain) + * W - water (traversable, but not passable from terrain) + * + */ + +/** + * Implementation note: + * For convenience, only '.' and 'G' are interpreted as walkable. + */ + +var fs = require('fs'); +var endOfLine = require('os').EOL; + +function parse(filename) { + var content = fs.readFileSync(filename).toString(); + var lines = content.split(endOfLine); + return { + height : parseInt(lines[1].split(' ')[1]), + width : parseInt(lines[2].split(' ')[1]), + grid : parseGrid(lines.slice(4)), + }; +} +exports.parse = parse; + +function parseGrid(lines) { + var grid = []; + lines.forEach(function(line) { + if (!line.length) { + return; + } + var row = []; + line.split('').forEach(function(char) { + row.push(char in { '.': 1, 'G': 1 } ? 0 : 1); + }); + grid.push(row); + }); + return grid; +} + +function splitext(filename) { + var index = filename.lastIndexOf('.'); + if (index < 0) { + return [filename, '']; + } else { + return [filename.substr(0, index), filename.substr(index)]; + } +} + +function main(argv) { + var filename = argv[2]; + var obj = parse(filename); + var root = splitext(filename)[0]; + fs.writeFileSync(root + '.json', JSON.stringify(obj)); +} + +if (!module.parent) { + main(process.argv); +} diff --git a/node_modules/pathfinding/benchmark/parse_scen.js b/node_modules/pathfinding/benchmark/parse_scen.js new file mode 100644 index 0000000..df0fc73 --- /dev/null +++ b/node_modules/pathfinding/benchmark/parse_scen.js @@ -0,0 +1,48 @@ +#!/usr/bin/env node + +/** + * The scenario files have the following format. + * The begin with the text "version x.x". This document describes version 1.0. + * The trailing 0 is optional. + * + * Each line of a scenario has 9 fields: + * + * Bucket + * map + * map width + * map height + * start x-coordinate + * start y-coordinate + * goal x-coordinate + * goal y-coordinate + * optimal length + */ + +var fs = require('fs'); + +function parse(filename) { + var content = fs.readFileSync(filename).toString(); + var lines = content.split('\n'); + var version = lines[1].split(/\s+/); + return { + version: version, + scenarios: lines.slice(1, lines.length - 1).map(parseLine) + }; +} + +function parseLine(line) { + var fields = line.split(/\s+/); + return { + bucket: parseInt(fields[0]), + map: fields[1], + width: parseInt(fields[2]), + height: parseInt(fields[3]), + startX: parseInt(fields[4]), + startY: parseInt(fields[5]), + endX: parseInt(fields[6]), + endY: parseInt(fields[7]), + length: parseFloat(fields[8]) + }; +} + +exports.parse = parse; diff --git a/node_modules/pathfinding/benchmark/scen/64room_000.map.scen b/node_modules/pathfinding/benchmark/scen/64room_000.map.scen new file mode 100644 index 0000000..892e4a1 --- /dev/null +++ b/node_modules/pathfinding/benchmark/scen/64room_000.map.scen @@ -0,0 +1,2031 @@ +version 1 +1 maps/rooms/64room_000.map 512 512 210 389 214 389 4 +1 maps/rooms/64room_000.map 512 512 137 295 134 292 4.24264 +1 maps/rooms/64room_000.map 512 512 71 507 65 510 7.24264 +1 maps/rooms/64room_000.map 512 512 474 427 469 426 5.41421 +1 maps/rooms/64room_000.map 512 512 291 14 295 15 4.41421 +1 maps/rooms/64room_000.map 512 512 227 214 225 220 6.82843 +1 maps/rooms/64room_000.map 512 512 68 315 74 316 6.41421 +1 maps/rooms/64room_000.map 512 512 456 113 456 108 5 +1 maps/rooms/64room_000.map 512 512 393 111 397 110 4.41421 +1 maps/rooms/64room_000.map 512 512 262 146 263 142 4.41421 +2 maps/rooms/64room_000.map 512 512 44 124 52 122 8.82843 +2 maps/rooms/64room_000.map 512 512 370 293 371 282 11.4142 +2 maps/rooms/64room_000.map 512 512 328 324 328 334 10 +2 maps/rooms/64room_000.map 512 512 343 130 339 138 9.65685 +2 maps/rooms/64room_000.map 512 512 45 333 49 323 11.6569 +2 maps/rooms/64room_000.map 512 512 111 85 106 79 8.07107 +2 maps/rooms/64room_000.map 512 512 41 143 43 152 9.82843 +2 maps/rooms/64room_000.map 512 512 374 461 374 471 10 +2 maps/rooms/64room_000.map 512 512 416 492 412 484 9.65685 +2 maps/rooms/64room_000.map 512 512 496 399 488 404 10.0711 +3 maps/rooms/64room_000.map 512 512 47 370 58 376 13.4853 +3 maps/rooms/64room_000.map 512 512 204 140 215 131 14.7279 +3 maps/rooms/64room_000.map 512 512 132 5 144 7 12.8284 +3 maps/rooms/64room_000.map 512 512 26 497 13 500 14.2426 +3 maps/rooms/64room_000.map 512 512 430 354 437 365 13.8995 +3 maps/rooms/64room_000.map 512 512 44 376 36 367 12.3137 +3 maps/rooms/64room_000.map 512 512 96 96 98 83 13.8284 +3 maps/rooms/64room_000.map 512 512 500 81 509 93 15.7279 +3 maps/rooms/64room_000.map 512 512 474 158 460 156 14.8284 +3 maps/rooms/64room_000.map 512 512 342 154 344 166 12.8284 +4 maps/rooms/64room_000.map 512 512 311 287 304 302 17.8995 +4 maps/rooms/64room_000.map 512 512 343 313 324 312 19.4142 +4 maps/rooms/64room_000.map 512 512 52 462 38 456 16.4853 +4 maps/rooms/64room_000.map 512 512 488 360 491 377 18.2426 +4 maps/rooms/64room_000.map 512 512 359 187 377 187 18 +4 maps/rooms/64room_000.map 512 512 398 39 391 25 16.8995 +4 maps/rooms/64room_000.map 512 512 38 102 38 118 16 +4 maps/rooms/64room_000.map 512 512 99 184 84 192 18.8995 +4 maps/rooms/64room_000.map 512 512 407 338 389 341 19.2426 +4 maps/rooms/64room_000.map 512 512 184 276 184 292 16 +5 maps/rooms/64room_000.map 512 512 163 347 182 344 20.2426 +5 maps/rooms/64room_000.map 512 512 259 404 281 404 22 +5 maps/rooms/64room_000.map 512 512 410 136 406 156 21.6569 +5 maps/rooms/64room_000.map 512 512 342 207 336 190 23.8284 +5 maps/rooms/64room_000.map 512 512 277 218 276 196 22.4142 +5 maps/rooms/64room_000.map 512 512 194 147 204 129 22.1421 +5 maps/rooms/64room_000.map 512 512 94 511 77 496 23.2132 +5 maps/rooms/64room_000.map 512 512 208 97 231 97 23 +5 maps/rooms/64room_000.map 512 512 420 47 400 38 23.7279 +5 maps/rooms/64room_000.map 512 512 415 170 438 170 23 +6 maps/rooms/64room_000.map 512 512 334 335 360 333 26.8284 +6 maps/rooms/64room_000.map 512 512 477 148 468 169 24.7279 +6 maps/rooms/64room_000.map 512 512 252 202 226 204 26.8284 +6 maps/rooms/64room_000.map 512 512 433 284 433 259 25 +6 maps/rooms/64room_000.map 512 512 395 495 401 471 26.4853 +6 maps/rooms/64room_000.map 512 512 110 493 132 497 26.1421 +6 maps/rooms/64room_000.map 512 512 229 284 210 265 26.8701 +6 maps/rooms/64room_000.map 512 512 223 476 205 458 25.4558 +6 maps/rooms/64room_000.map 512 512 152 497 162 477 24.1421 +6 maps/rooms/64room_000.map 512 512 451 247 444 225 26.6569 +7 maps/rooms/64room_000.map 512 512 121 155 103 178 30.4558 +7 maps/rooms/64room_000.map 512 512 58 463 78 482 29.6274 +7 maps/rooms/64room_000.map 512 512 154 418 149 447 31.0711 +7 maps/rooms/64room_000.map 512 512 329 275 352 290 29.2132 +7 maps/rooms/64room_000.map 512 512 366 190 378 166 28.9706 +7 maps/rooms/64room_000.map 512 512 333 423 324 398 28.7279 +7 maps/rooms/64room_000.map 512 512 279 188 277 157 31.8284 +7 maps/rooms/64room_000.map 512 512 397 416 403 387 31.4853 +7 maps/rooms/64room_000.map 512 512 105 136 97 162 29.3137 +7 maps/rooms/64room_000.map 512 512 478 377 508 379 30.8284 +8 maps/rooms/64room_000.map 512 512 370 455 376 428 33.7279 +8 maps/rooms/64room_000.map 512 512 29 211 45 237 32.6274 +8 maps/rooms/64room_000.map 512 512 169 65 140 76 33.5563 +8 maps/rooms/64room_000.map 512 512 195 59 179 32 34.799 +8 maps/rooms/64room_000.map 512 512 421 371 391 380 33.7279 +8 maps/rooms/64room_000.map 512 512 124 350 108 321 35.6274 +8 maps/rooms/64room_000.map 512 512 346 325 325 308 35.799 +8 maps/rooms/64room_000.map 512 512 105 162 80 180 32.4558 +8 maps/rooms/64room_000.map 512 512 1 475 30 491 35.6274 +8 maps/rooms/64room_000.map 512 512 251 233 247 200 34.6569 +9 maps/rooms/64room_000.map 512 512 88 325 90 311 38.9706 +9 maps/rooms/64room_000.map 512 512 58 484 79 459 38.9706 +9 maps/rooms/64room_000.map 512 512 74 342 55 312 39.0416 +9 maps/rooms/64room_000.map 512 512 243 300 232 268 36.5563 +9 maps/rooms/64room_000.map 512 512 500 472 497 438 38.5563 +9 maps/rooms/64room_000.map 512 512 72 283 97 309 36.3553 +9 maps/rooms/64room_000.map 512 512 50 91 15 82 38.7279 +9 maps/rooms/64room_000.map 512 512 505 268 471 273 36.0711 +9 maps/rooms/64room_000.map 512 512 84 199 87 235 37.2426 +9 maps/rooms/64room_000.map 512 512 433 255 420 223 37.3848 +10 maps/rooms/64room_000.map 512 512 441 78 411 48 43.598 +10 maps/rooms/64room_000.map 512 512 65 191 67 151 40.8284 +10 maps/rooms/64room_000.map 512 512 156 447 145 460 41.5563 +10 maps/rooms/64room_000.map 512 512 508 432 477 405 42.1838 +10 maps/rooms/64room_000.map 512 512 174 156 142 183 43.1838 +10 maps/rooms/64room_000.map 512 512 243 183 205 177 40.4853 +10 maps/rooms/64room_000.map 512 512 377 316 361 279 43.6274 +10 maps/rooms/64room_000.map 512 512 303 407 318 442 41.2132 +10 maps/rooms/64room_000.map 512 512 116 304 118 262 42.8284 +10 maps/rooms/64room_000.map 512 512 148 267 171 244 43.799 +11 maps/rooms/64room_000.map 512 512 313 176 304 134 45.7279 +11 maps/rooms/64room_000.map 512 512 80 30 119 14 45.6274 +11 maps/rooms/64room_000.map 512 512 463 446 502 430 45.6274 +11 maps/rooms/64room_000.map 512 512 184 235 157 200 46.1838 +11 maps/rooms/64room_000.map 512 512 123 391 118 435 46.0711 +11 maps/rooms/64room_000.map 512 512 18 233 59 220 46.3848 +11 maps/rooms/64room_000.map 512 512 72 415 74 460 47.4853 +11 maps/rooms/64room_000.map 512 512 215 238 207 280 47.799 +11 maps/rooms/64room_000.map 512 512 337 346 380 354 46.3137 +11 maps/rooms/64room_000.map 512 512 253 261 218 291 47.4264 +12 maps/rooms/64room_000.map 512 512 452 14 467 59 51.2132 +12 maps/rooms/64room_000.map 512 512 469 214 441 205 51.8701 +12 maps/rooms/64room_000.map 512 512 315 118 306 70 51.7279 +12 maps/rooms/64room_000.map 512 512 187 102 221 102 48.6274 +12 maps/rooms/64room_000.map 512 512 206 63 237 27 48.8406 +12 maps/rooms/64room_000.map 512 512 107 145 152 141 49.9706 +12 maps/rooms/64room_000.map 512 512 362 365 333 328 49.0122 +12 maps/rooms/64room_000.map 512 512 70 299 87 342 50.0416 +12 maps/rooms/64room_000.map 512 512 389 118 415 77 51.7696 +12 maps/rooms/64room_000.map 512 512 507 116 488 157 50.5269 +13 maps/rooms/64room_000.map 512 512 78 152 125 168 53.6274 +13 maps/rooms/64room_000.map 512 512 48 189 41 136 55.8995 +13 maps/rooms/64room_000.map 512 512 261 235 220 203 54.2548 +13 maps/rooms/64room_000.map 512 512 155 257 156 218 53.5563 +13 maps/rooms/64room_000.map 512 512 299 432 348 444 53.9706 +13 maps/rooms/64room_000.map 512 512 213 334 171 348 54.1838 +13 maps/rooms/64room_000.map 512 512 385 113 410 157 54.3553 +13 maps/rooms/64room_000.map 512 512 171 329 183 380 55.9706 +13 maps/rooms/64room_000.map 512 512 172 211 213 247 55.9117 +13 maps/rooms/64room_000.map 512 512 400 235 443 206 55.0122 +14 maps/rooms/64room_000.map 512 512 503 44 492 91 58.1838 +14 maps/rooms/64room_000.map 512 512 401 398 381 387 58.4558 +14 maps/rooms/64room_000.map 512 512 393 52 372 84 57.0416 +14 maps/rooms/64room_000.map 512 512 442 228 447 186 58.8995 +14 maps/rooms/64room_000.map 512 512 62 435 14 454 57.0416 +14 maps/rooms/64room_000.map 512 512 291 52 259 6 59.2548 +14 maps/rooms/64room_000.map 512 512 335 276 352 224 59.0416 +14 maps/rooms/64room_000.map 512 512 489 219 456 180 58.1838 +14 maps/rooms/64room_000.map 512 512 213 80 199 35 57.2843 +14 maps/rooms/64room_000.map 512 512 106 5 107 62 57.4142 +15 maps/rooms/64room_000.map 512 512 454 354 445 366 60.8995 +15 maps/rooms/64room_000.map 512 512 387 147 362 151 61.5269 +15 maps/rooms/64room_000.map 512 512 436 377 387 344 62.669 +15 maps/rooms/64room_000.map 512 512 396 395 353 430 63.9411 +15 maps/rooms/64room_000.map 512 512 490 180 443 177 63.2132 +15 maps/rooms/64room_000.map 512 512 353 68 410 63 61.8995 +15 maps/rooms/64room_000.map 512 512 243 198 272 227 60.8701 +15 maps/rooms/64room_000.map 512 512 120 149 66 130 61.8701 +15 maps/rooms/64room_000.map 512 512 310 209 291 265 63.8701 +15 maps/rooms/64room_000.map 512 512 310 170 262 140 60.4264 +16 maps/rooms/64room_000.map 512 512 291 195 310 152 65.0711 +16 maps/rooms/64room_000.map 512 512 178 112 243 119 67.8995 +16 maps/rooms/64room_000.map 512 512 350 52 359 108 67.0416 +16 maps/rooms/64room_000.map 512 512 79 337 50 288 65.1127 +16 maps/rooms/64room_000.map 512 512 475 72 430 120 67.8112 +16 maps/rooms/64room_000.map 512 512 380 333 441 338 66.9706 +16 maps/rooms/64room_000.map 512 512 69 352 101 313 65.1421 +16 maps/rooms/64room_000.map 512 512 372 125 325 156 64.5269 +16 maps/rooms/64room_000.map 512 512 508 381 453 355 65.7696 +16 maps/rooms/64room_000.map 512 512 507 118 455 82 66.9117 +17 maps/rooms/64room_000.map 512 512 167 193 115 219 70.3848 +17 maps/rooms/64room_000.map 512 512 189 114 244 145 69.0122 +17 maps/rooms/64room_000.map 512 512 317 259 273 218 70.9411 +17 maps/rooms/64room_000.map 512 512 45 505 37 447 70.2426 +17 maps/rooms/64room_000.map 512 512 419 59 396 109 68.4975 +17 maps/rooms/64room_000.map 512 512 280 416 232 416 71.0538 +17 maps/rooms/64room_000.map 512 512 371 357 338 302 68.669 +17 maps/rooms/64room_000.map 512 512 61 358 37 297 70.9411 +17 maps/rooms/64room_000.map 512 512 295 229 277 292 70.4558 +17 maps/rooms/64room_000.map 512 512 188 386 154 330 71.8406 +18 maps/rooms/64room_000.map 512 512 350 301 284 291 74.2843 +18 maps/rooms/64room_000.map 512 512 286 205 282 174 72.0122 +18 maps/rooms/64room_000.map 512 512 177 411 235 410 72.8406 +18 maps/rooms/64room_000.map 512 512 349 79 421 82 73.2426 +18 maps/rooms/64room_000.map 512 512 193 103 223 52 73.9706 +18 maps/rooms/64room_000.map 512 512 386 184 329 191 73.4558 +18 maps/rooms/64room_000.map 512 512 48 268 36 246 74.2843 +18 maps/rooms/64room_000.map 512 512 266 53 245 69 73.0833 +18 maps/rooms/64room_000.map 512 512 200 65 139 61 75.7279 +18 maps/rooms/64room_000.map 512 512 206 481 213 417 72.6985 +19 maps/rooms/64room_000.map 512 512 238 424 293 392 78.4558 +19 maps/rooms/64room_000.map 512 512 431 493 366 464 77.0122 +19 maps/rooms/64room_000.map 512 512 335 284 266 308 78.9411 +19 maps/rooms/64room_000.map 512 512 113 138 59 103 77.8701 +19 maps/rooms/64room_000.map 512 512 349 273 344 203 79.5269 +19 maps/rooms/64room_000.map 512 512 268 171 235 130 79.8406 +19 maps/rooms/64room_000.map 512 512 54 136 10 109 79.6274 +19 maps/rooms/64room_000.map 512 512 409 420 382 463 76.1421 +19 maps/rooms/64room_000.map 512 512 227 189 177 211 78.7107 +19 maps/rooms/64room_000.map 512 512 26 59 74 60 76.2548 +20 maps/rooms/64room_000.map 512 512 77 273 43 338 83.7696 +20 maps/rooms/64room_000.map 512 512 70 342 46 272 81.1127 +20 maps/rooms/64room_000.map 512 512 349 293 276 270 82.5269 +20 maps/rooms/64room_000.map 512 512 441 176 508 182 82.2132 +20 maps/rooms/64room_000.map 512 512 144 17 200 39 80.8112 +20 maps/rooms/64room_000.map 512 512 325 62 359 101 80.8995 +20 maps/rooms/64room_000.map 512 512 276 111 312 56 82.2132 +20 maps/rooms/64room_000.map 512 512 399 1 368 63 83.6274 +20 maps/rooms/64room_000.map 512 512 491 414 452 464 83.0416 +20 maps/rooms/64room_000.map 512 512 96 267 167 275 82.598 +21 maps/rooms/64room_000.map 512 512 40 280 27 339 84.0833 +21 maps/rooms/64room_000.map 512 512 193 233 255 292 87.6102 +21 maps/rooms/64room_000.map 512 512 342 444 258 447 85.2426 +21 maps/rooms/64room_000.map 512 512 502 422 474 498 87.598 +21 maps/rooms/64room_000.map 512 512 96 244 96 166 87.9411 +21 maps/rooms/64room_000.map 512 512 18 60 54 120 85.8822 +21 maps/rooms/64room_000.map 512 512 459 443 492 495 84.0711 +21 maps/rooms/64room_000.map 512 512 432 316 362 279 85.3259 +21 maps/rooms/64room_000.map 512 512 71 290 126 326 86.8995 +21 maps/rooms/64room_000.map 512 512 240 178 258 246 85.7401 +22 maps/rooms/64room_000.map 512 512 305 389 242 358 89.2132 +22 maps/rooms/64room_000.map 512 512 52 417 113 409 88.9828 +22 maps/rooms/64room_000.map 512 512 509 226 434 191 90.669 +22 maps/rooms/64room_000.map 512 512 432 254 376 239 89.2254 +22 maps/rooms/64room_000.map 512 512 244 251 163 225 91.7696 +22 maps/rooms/64room_000.map 512 512 417 150 375 215 91.0833 +22 maps/rooms/64room_000.map 512 512 123 161 69 225 91.6396 +22 maps/rooms/64room_000.map 512 512 409 430 462 385 90.3848 +22 maps/rooms/64room_000.map 512 512 288 193 296 278 88.3137 +22 maps/rooms/64room_000.map 512 512 189 475 114 487 90.7401 +23 maps/rooms/64room_000.map 512 512 171 429 152 360 92.9117 +23 maps/rooms/64room_000.map 512 512 303 126 265 50 95.2548 +23 maps/rooms/64room_000.map 512 512 141 338 219 329 95.8112 +23 maps/rooms/64room_000.map 512 512 98 240 151 294 92.9411 +23 maps/rooms/64room_000.map 512 512 67 267 25 321 94.2426 +23 maps/rooms/64room_000.map 512 512 304 314 235 271 94.4264 +23 maps/rooms/64room_000.map 512 512 324 311 299 232 93.8406 +23 maps/rooms/64room_000.map 512 512 254 49 315 8 92.6274 +23 maps/rooms/64room_000.map 512 512 315 433 242 402 94.9533 +23 maps/rooms/64room_000.map 512 512 243 372 160 346 93.7696 +24 maps/rooms/64room_000.map 512 512 409 152 370 233 98.3259 +24 maps/rooms/64room_000.map 512 512 119 126 181 96 99.8822 +24 maps/rooms/64room_000.map 512 512 76 374 107 304 96.4558 +24 maps/rooms/64room_000.map 512 512 464 447 471 505 96.1127 +24 maps/rooms/64room_000.map 512 512 495 46 449 93 99.2254 +24 maps/rooms/64room_000.map 512 512 438 497 370 441 99.397 +24 maps/rooms/64room_000.map 512 512 35 84 101 71 99.5097 +24 maps/rooms/64room_000.map 512 512 505 181 415 182 97.8701 +24 maps/rooms/64room_000.map 512 512 30 402 12 328 97.598 +24 maps/rooms/64room_000.map 512 512 340 331 363 419 97.5269 +25 maps/rooms/64room_000.map 512 512 407 141 355 87 100.184 +25 maps/rooms/64room_000.map 512 512 386 426 303 443 103.012 +25 maps/rooms/64room_000.map 512 512 411 250 416 152 101.728 +25 maps/rooms/64room_000.map 512 512 284 187 244 225 100.184 +25 maps/rooms/64room_000.map 512 512 346 304 434 270 102.083 +25 maps/rooms/64room_000.map 512 512 350 147 394 208 100.439 +25 maps/rooms/64room_000.map 512 512 154 259 60 240 103.042 +25 maps/rooms/64room_000.map 512 512 375 72 356 158 102.154 +25 maps/rooms/64room_000.map 512 512 36 272 44 362 103.255 +25 maps/rooms/64room_000.map 512 512 140 292 98 224 102.385 +26 maps/rooms/64room_000.map 512 512 34 410 119 416 106.539 +26 maps/rooms/64room_000.map 512 512 378 55 335 138 104.912 +26 maps/rooms/64room_000.map 512 512 92 92 30 26 106.326 +26 maps/rooms/64room_000.map 512 512 374 137 376 202 105.569 +26 maps/rooms/64room_000.map 512 512 112 282 85 189 105.012 +26 maps/rooms/64room_000.map 512 512 357 392 445 403 104.154 +26 maps/rooms/64room_000.map 512 512 416 338 501 304 106.113 +26 maps/rooms/64room_000.map 512 512 265 437 221 430 104.397 +26 maps/rooms/64room_000.map 512 512 461 273 408 337 107.042 +26 maps/rooms/64room_000.map 512 512 435 234 470 146 106.598 +27 maps/rooms/64room_000.map 512 512 462 144 484 241 111.912 +27 maps/rooms/64room_000.map 512 512 334 108 264 138 111.698 +27 maps/rooms/64room_000.map 512 512 248 95 187 69 111.527 +27 maps/rooms/64room_000.map 512 512 80 218 141 287 111.255 +27 maps/rooms/64room_000.map 512 512 474 408 381 412 111.326 +27 maps/rooms/64room_000.map 512 512 208 69 262 13 109.296 +27 maps/rooms/64room_000.map 512 512 332 195 428 164 110.012 +27 maps/rooms/64room_000.map 512 512 379 90 417 168 110.912 +27 maps/rooms/64room_000.map 512 512 16 297 23 194 110.87 +27 maps/rooms/64room_000.map 512 512 200 65 293 56 109.497 +28 maps/rooms/64room_000.map 512 512 121 499 20 465 115.083 +28 maps/rooms/64room_000.map 512 512 210 300 312 280 113.598 +28 maps/rooms/64room_000.map 512 512 398 19 378 102 112.598 +28 maps/rooms/64room_000.map 512 512 175 102 222 35 113.983 +28 maps/rooms/64room_000.map 512 512 129 127 227 135 113.255 +28 maps/rooms/64room_000.map 512 512 327 466 398 406 112.255 +28 maps/rooms/64room_000.map 512 512 206 415 205 351 113.426 +28 maps/rooms/64room_000.map 512 512 9 77 44 171 115.711 +28 maps/rooms/64room_000.map 512 512 382 93 291 53 115.184 +28 maps/rooms/64room_000.map 512 512 333 305 308 204 114.77 +29 maps/rooms/64room_000.map 512 512 399 318 302 281 117.012 +29 maps/rooms/64room_000.map 512 512 186 396 174 283 117.971 +29 maps/rooms/64room_000.map 512 512 423 61 510 116 118.569 +29 maps/rooms/64room_000.map 512 512 491 360 438 415 118.083 +29 maps/rooms/64room_000.map 512 512 339 21 376 122 116.326 +29 maps/rooms/64room_000.map 512 512 333 194 441 212 119.598 +29 maps/rooms/64room_000.map 512 512 453 327 375 299 116.385 +29 maps/rooms/64room_000.map 512 512 55 215 99 169 119.397 +29 maps/rooms/64room_000.map 512 512 213 402 311 430 118.711 +29 maps/rooms/64room_000.map 512 512 463 364 426 316 116.497 +30 maps/rooms/64room_000.map 512 512 354 222 326 125 121.627 +30 maps/rooms/64room_000.map 512 512 405 416 457 362 121.113 +30 maps/rooms/64room_000.map 512 512 396 187 310 144 120.924 +30 maps/rooms/64room_000.map 512 512 100 61 34 86 123.326 +30 maps/rooms/64room_000.map 512 512 424 433 455 335 123.728 +30 maps/rooms/64room_000.map 512 512 47 396 21 323 120.841 +30 maps/rooms/64room_000.map 512 512 287 211 253 311 121.882 +30 maps/rooms/64room_000.map 512 512 430 494 323 475 123.154 +30 maps/rooms/64room_000.map 512 512 60 423 139 504 121.338 +30 maps/rooms/64room_000.map 512 512 430 380 354 390 122.426 +31 maps/rooms/64room_000.map 512 512 231 154 268 101 124.267 +31 maps/rooms/64room_000.map 512 512 83 383 9 316 124.598 +31 maps/rooms/64room_000.map 512 512 166 252 234 298 125.338 +31 maps/rooms/64room_000.map 512 512 47 147 10 59 127.184 +31 maps/rooms/64room_000.map 512 512 118 397 60 386 126.64 +31 maps/rooms/64room_000.map 512 512 331 112 332 13 126.752 +31 maps/rooms/64room_000.map 512 512 233 211 323 219 125.255 +31 maps/rooms/64room_000.map 512 512 179 149 194 85 127.083 +31 maps/rooms/64room_000.map 512 512 511 252 398 234 126.255 +31 maps/rooms/64room_000.map 512 512 115 385 160 342 126.225 +32 maps/rooms/64room_000.map 512 512 3 402 91 495 130.622 +32 maps/rooms/64room_000.map 512 512 188 224 122 248 129.497 +32 maps/rooms/64room_000.map 512 512 247 129 133 134 130.841 +32 maps/rooms/64room_000.map 512 512 444 307 385 343 131.627 +32 maps/rooms/64room_000.map 512 512 430 259 468 372 129.912 +32 maps/rooms/64room_000.map 512 512 131 348 255 346 130.627 +32 maps/rooms/64room_000.map 512 512 228 182 138 199 128.095 +32 maps/rooms/64room_000.map 512 512 204 94 157 174 129.912 +32 maps/rooms/64room_000.map 512 512 86 175 41 200 128.811 +32 maps/rooms/64room_000.map 512 512 183 124 71 169 131.811 +33 maps/rooms/64room_000.map 512 512 283 62 238 152 134.823 +33 maps/rooms/64room_000.map 512 512 323 323 435 379 135.196 +33 maps/rooms/64room_000.map 512 512 309 55 197 103 133.054 +33 maps/rooms/64room_000.map 512 512 277 236 238 138 133.326 +33 maps/rooms/64room_000.map 512 512 228 160 329 135 135.38 +33 maps/rooms/64room_000.map 512 512 271 186 230 88 132.539 +33 maps/rooms/64room_000.map 512 512 247 309 165 234 135.267 +33 maps/rooms/64room_000.map 512 512 292 200 347 309 133.539 +33 maps/rooms/64room_000.map 512 512 293 270 369 366 134.51 +33 maps/rooms/64room_000.map 512 512 445 340 329 304 132.083 +34 maps/rooms/64room_000.map 512 512 406 428 459 464 137.083 +34 maps/rooms/64room_000.map 512 512 239 123 157 26 136.238 +34 maps/rooms/64room_000.map 512 512 352 125 442 198 139.267 +34 maps/rooms/64room_000.map 512 512 361 338 378 250 138.841 +34 maps/rooms/64room_000.map 512 512 247 75 245 190 138.196 +34 maps/rooms/64room_000.map 512 512 356 396 341 265 137.213 +34 maps/rooms/64room_000.map 512 512 92 317 44 218 139.569 +34 maps/rooms/64room_000.map 512 512 482 252 362 205 139.468 +34 maps/rooms/64room_000.map 512 512 153 317 196 217 136.154 +34 maps/rooms/64room_000.map 512 512 279 133 263 226 137.752 +35 maps/rooms/64room_000.map 512 512 354 405 317 281 140.497 +35 maps/rooms/64room_000.map 512 512 295 59 386 116 140.083 +35 maps/rooms/64room_000.map 512 512 244 13 233 118 141.865 +35 maps/rooms/64room_000.map 512 512 86 337 53 431 140.924 +35 maps/rooms/64room_000.map 512 512 244 142 285 238 140.64 +35 maps/rooms/64room_000.map 512 512 308 295 437 286 141.012 +35 maps/rooms/64room_000.map 512 512 211 299 166 416 141.74 +35 maps/rooms/64room_000.map 512 512 176 27 154 97 142.083 +35 maps/rooms/64room_000.map 512 512 332 25 387 131 140.681 +35 maps/rooms/64room_000.map 512 512 430 81 370 149 142.024 +36 maps/rooms/64room_000.map 512 512 356 93 479 126 145.782 +36 maps/rooms/64room_000.map 512 512 139 144 247 68 145.924 +36 maps/rooms/64room_000.map 512 512 309 443 352 510 145.841 +36 maps/rooms/64room_000.map 512 512 124 137 2 83 145.539 +36 maps/rooms/64room_000.map 512 512 379 97 369 206 144.054 +36 maps/rooms/64room_000.map 512 512 431 253 351 154 144.439 +36 maps/rooms/64room_000.map 512 512 84 281 133 366 147.213 +36 maps/rooms/64room_000.map 512 512 112 264 5 282 146.74 +36 maps/rooms/64room_000.map 512 512 101 507 15 399 144.794 +36 maps/rooms/64room_000.map 512 512 227 101 296 175 145.368 +37 maps/rooms/64room_000.map 512 512 244 223 142 290 148.497 +37 maps/rooms/64room_000.map 512 512 305 202 413 218 150.569 +37 maps/rooms/64room_000.map 512 512 451 263 386 372 149.397 +37 maps/rooms/64room_000.map 512 512 451 123 382 180 151.397 +37 maps/rooms/64room_000.map 512 512 329 229 375 360 150.054 +37 maps/rooms/64room_000.map 512 512 458 509 434 447 151.924 +37 maps/rooms/64room_000.map 512 512 423 274 319 254 148.652 +37 maps/rooms/64room_000.map 512 512 349 471 297 407 148.468 +37 maps/rooms/64room_000.map 512 512 323 355 285 435 151.095 +37 maps/rooms/64room_000.map 512 512 114 145 122 55 151.296 +38 maps/rooms/64room_000.map 512 512 359 324 237 315 153.853 +38 maps/rooms/64room_000.map 512 512 358 159 325 53 152.983 +38 maps/rooms/64room_000.map 512 512 330 303 372 174 153.426 +38 maps/rooms/64room_000.map 512 512 159 316 58 329 155.556 +38 maps/rooms/64room_000.map 512 512 102 467 70 360 154.581 +38 maps/rooms/64room_000.map 512 512 159 371 161 475 155.865 +38 maps/rooms/64room_000.map 512 512 163 13 204 133 155.61 +38 maps/rooms/64room_000.map 512 512 276 439 343 471 153.426 +38 maps/rooms/64room_000.map 512 512 96 308 190 339 154.012 +38 maps/rooms/64room_000.map 512 512 292 241 398 168 154.054 +39 maps/rooms/64room_000.map 512 512 251 224 158 289 158.225 +39 maps/rooms/64room_000.map 512 512 153 467 156 353 156.179 +39 maps/rooms/64room_000.map 512 512 294 228 422 299 158.581 +39 maps/rooms/64room_000.map 512 512 151 293 37 213 158.267 +39 maps/rooms/64room_000.map 512 512 228 305 160 415 157.154 +39 maps/rooms/64room_000.map 512 512 338 187 438 100 157.711 +39 maps/rooms/64room_000.map 512 512 142 266 26 343 156.522 +39 maps/rooms/64room_000.map 512 512 35 314 38 410 159.208 +39 maps/rooms/64room_000.map 512 512 261 160 153 202 158.409 +39 maps/rooms/64room_000.map 512 512 341 354 271 231 159.794 +40 maps/rooms/64room_000.map 512 512 340 241 219 281 160.841 +40 maps/rooms/64room_000.map 512 512 392 257 272 290 160.698 +40 maps/rooms/64room_000.map 512 512 52 194 143 237 162.77 +40 maps/rooms/64room_000.map 512 512 465 132 364 219 163.397 +40 maps/rooms/64room_000.map 512 512 285 289 210 182 163.338 +40 maps/rooms/64room_000.map 512 512 152 183 207 141 161.225 +40 maps/rooms/64room_000.map 512 512 162 504 27 440 163.51 +40 maps/rooms/64room_000.map 512 512 251 204 364 203 160.125 +40 maps/rooms/64room_000.map 512 512 338 151 310 293 160.083 +40 maps/rooms/64room_000.map 512 512 141 58 231 144 160.811 +41 maps/rooms/64room_000.map 512 512 420 172 333 62 165.953 +41 maps/rooms/64room_000.map 512 512 65 293 13 423 166.167 +41 maps/rooms/64room_000.map 512 512 413 220 354 317 164.853 +41 maps/rooms/64room_000.map 512 512 266 147 369 199 164.054 +41 maps/rooms/64room_000.map 512 512 367 289 280 168 164.652 +41 maps/rooms/64room_000.map 512 512 451 222 503 81 167.51 +41 maps/rooms/64room_000.map 512 512 159 80 70 194 164.338 +41 maps/rooms/64room_000.map 512 512 250 101 226 244 165.569 +41 maps/rooms/64room_000.map 512 512 112 374 89 238 167.894 +41 maps/rooms/64room_000.map 512 512 118 341 165 431 166.38 +42 maps/rooms/64room_000.map 512 512 338 274 463 331 170.527 +42 maps/rooms/64room_000.map 512 512 180 359 185 460 169.338 +42 maps/rooms/64room_000.map 512 512 344 316 492 370 171.539 +42 maps/rooms/64room_000.map 512 512 139 164 71 249 168.338 +42 maps/rooms/64room_000.map 512 512 439 459 433 442 170.154 +42 maps/rooms/64room_000.map 512 512 115 259 193 383 168.51 +42 maps/rooms/64room_000.map 512 512 287 412 422 477 170.125 +42 maps/rooms/64room_000.map 512 512 396 475 347 329 168.054 +42 maps/rooms/64room_000.map 512 512 88 173 36 266 170.64 +42 maps/rooms/64room_000.map 512 512 484 190 395 81 168.953 +43 maps/rooms/64room_000.map 512 512 127 226 155 167 173.25 +43 maps/rooms/64room_000.map 512 512 249 187 275 301 175.782 +43 maps/rooms/64room_000.map 512 512 140 135 105 16 174.551 +43 maps/rooms/64room_000.map 512 512 236 160 251 311 172.125 +43 maps/rooms/64room_000.map 512 512 342 117 293 259 173.225 +43 maps/rooms/64room_000.map 512 512 177 457 200 359 175.995 +43 maps/rooms/64room_000.map 512 512 251 392 385 422 172.551 +43 maps/rooms/64room_000.map 512 512 19 476 76 357 173.421 +43 maps/rooms/64room_000.map 512 512 290 19 188 123 172.024 +43 maps/rooms/64room_000.map 512 512 207 175 331 224 173.853 +44 maps/rooms/64room_000.map 512 512 502 440 411 354 177.066 +44 maps/rooms/64room_000.map 512 512 122 290 10 395 176.421 +44 maps/rooms/64room_000.map 512 512 413 39 297 89 176.953 +44 maps/rooms/64room_000.map 512 512 237 414 187 287 178.539 +44 maps/rooms/64room_000.map 512 512 108 207 50 358 176.782 +44 maps/rooms/64room_000.map 512 512 158 284 11 259 176.368 +44 maps/rooms/64room_000.map 512 512 187 88 298 172 178.924 +44 maps/rooms/64room_000.map 512 512 398 346 297 440 177.225 +44 maps/rooms/64room_000.map 512 512 510 187 459 58 179.314 +44 maps/rooms/64room_000.map 512 512 130 81 38 121 178.953 +45 maps/rooms/64room_000.map 512 512 487 228 343 137 182.865 +45 maps/rooms/64room_000.map 512 512 440 223 303 291 180.095 +45 maps/rooms/64room_000.map 512 512 365 48 202 71 180.326 +45 maps/rooms/64room_000.map 512 512 293 311 247 177 183.095 +45 maps/rooms/64room_000.map 512 512 294 26 441 106 182.48 +45 maps/rooms/64room_000.map 512 512 82 330 37 196 180.279 +45 maps/rooms/64room_000.map 512 512 455 183 352 81 180.581 +45 maps/rooms/64room_000.map 512 512 149 371 158 224 182.208 +45 maps/rooms/64room_000.map 512 512 180 462 103 419 182.049 +45 maps/rooms/64room_000.map 512 512 353 505 309 397 181.154 +46 maps/rooms/64room_000.map 512 512 86 63 35 164 187.196 +46 maps/rooms/64room_000.map 512 512 213 258 354 193 185.095 +46 maps/rooms/64room_000.map 512 512 403 385 297 283 185.154 +46 maps/rooms/64room_000.map 512 512 282 272 389 151 187.581 +46 maps/rooms/64room_000.map 512 512 136 367 105 255 187.083 +46 maps/rooms/64room_000.map 512 512 214 410 98 487 187.368 +46 maps/rooms/64room_000.map 512 512 281 59 130 127 186.924 +46 maps/rooms/64room_000.map 512 512 356 365 436 500 184.48 +46 maps/rooms/64room_000.map 512 512 393 289 464 413 185.627 +46 maps/rooms/64room_000.map 512 512 110 270 213 327 186.35 +47 maps/rooms/64room_000.map 512 512 363 251 373 388 190.698 +47 maps/rooms/64room_000.map 512 512 241 275 163 423 189.338 +47 maps/rooms/64room_000.map 512 512 68 472 153 392 190.539 +47 maps/rooms/64room_000.map 512 512 17 337 24 489 188.037 +47 maps/rooms/64room_000.map 512 512 341 56 180 49 188.752 +47 maps/rooms/64room_000.map 512 512 283 51 153 66 191.451 +47 maps/rooms/64room_000.map 512 512 250 442 127 501 189.154 +47 maps/rooms/64room_000.map 512 512 275 172 395 208 189.439 +47 maps/rooms/64room_000.map 512 512 238 205 179 44 188.368 +47 maps/rooms/64room_000.map 512 512 414 345 304 421 190.409 +48 maps/rooms/64room_000.map 512 512 163 471 136 335 194.12 +48 maps/rooms/64room_000.map 512 512 435 222 261 220 195.539 +48 maps/rooms/64room_000.map 512 512 116 443 8 329 193.539 +48 maps/rooms/64room_000.map 512 512 118 337 233 428 195.823 +48 maps/rooms/64room_000.map 512 512 453 239 392 72 195.782 +48 maps/rooms/64room_000.map 512 512 210 360 122 302 193.823 +48 maps/rooms/64room_000.map 512 512 249 252 368 159 192.267 +48 maps/rooms/64room_000.map 512 512 109 124 140 259 193.296 +48 maps/rooms/64room_000.map 512 512 382 465 495 466 193.154 +48 maps/rooms/64room_000.map 512 512 259 311 322 170 192.108 +49 maps/rooms/64room_000.map 512 512 324 403 203 428 197.522 +49 maps/rooms/64room_000.map 512 512 376 191 447 24 197.581 +49 maps/rooms/64room_000.map 512 512 347 353 250 390 196.794 +49 maps/rooms/64room_000.map 512 512 106 219 227 159 198.279 +49 maps/rooms/64room_000.map 512 512 342 444 471 341 199.037 +49 maps/rooms/64room_000.map 512 512 307 180 142 195 198.894 +49 maps/rooms/64room_000.map 512 512 322 227 449 262 196.024 +49 maps/rooms/64room_000.map 512 512 215 189 105 152 198.539 +49 maps/rooms/64room_000.map 512 512 356 327 427 237 197.309 +49 maps/rooms/64room_000.map 512 512 213 258 337 331 199.593 +50 maps/rooms/64room_000.map 512 512 137 121 270 149 201.995 +50 maps/rooms/64room_000.map 512 512 335 291 427 441 200.995 +50 maps/rooms/64room_000.map 512 512 78 258 152 120 200.066 +50 maps/rooms/64room_000.map 512 512 294 223 117 200 200.61 +50 maps/rooms/64room_000.map 512 512 371 100 259 228 201.338 +50 maps/rooms/64room_000.map 512 512 44 362 26 505 202.279 +50 maps/rooms/64room_000.map 512 512 340 296 160 330 203.539 +50 maps/rooms/64room_000.map 512 512 87 266 214 376 201.108 +50 maps/rooms/64room_000.map 512 512 276 141 241 299 203.267 +50 maps/rooms/64room_000.map 512 512 80 227 251 232 200.409 +51 maps/rooms/64room_000.map 512 512 14 285 200 316 205.326 +51 maps/rooms/64room_000.map 512 512 439 261 367 402 205.066 +51 maps/rooms/64room_000.map 512 512 140 334 251 477 204.208 +51 maps/rooms/64room_000.map 512 512 360 336 412 509 204.823 +51 maps/rooms/64room_000.map 512 512 294 316 412 167 206.078 +51 maps/rooms/64room_000.map 512 512 488 310 376 443 205.167 +51 maps/rooms/64room_000.map 512 512 312 78 349 135 205.782 +51 maps/rooms/64room_000.map 512 512 46 118 204 85 204.439 +51 maps/rooms/64room_000.map 512 512 65 248 221 280 207.764 +51 maps/rooms/64room_000.map 512 512 166 311 4 310 207.042 +52 maps/rooms/64room_000.map 512 512 77 340 215 223 210.279 +52 maps/rooms/64room_000.map 512 512 305 43 237 199 210.451 +52 maps/rooms/64room_000.map 512 512 45 35 169 102 209.451 +52 maps/rooms/64room_000.map 512 512 266 223 417 340 209.421 +52 maps/rooms/64room_000.map 512 512 141 289 193 386 208.74 +52 maps/rooms/64room_000.map 512 512 317 207 479 229 211.154 +52 maps/rooms/64room_000.map 512 512 78 488 209 401 211.539 +52 maps/rooms/64room_000.map 512 512 249 243 231 381 209.823 +52 maps/rooms/64room_000.map 512 512 458 493 373 439 209.066 +52 maps/rooms/64room_000.map 512 512 96 98 193 37 210.468 +53 maps/rooms/64room_000.map 512 512 450 162 347 60 214.38 +53 maps/rooms/64room_000.map 512 512 302 255 228 95 214.167 +53 maps/rooms/64room_000.map 512 512 272 186 93 261 214.894 +53 maps/rooms/64room_000.map 512 512 299 218 430 323 212.267 +53 maps/rooms/64room_000.map 512 512 67 264 158 131 213.823 +53 maps/rooms/64room_000.map 512 512 40 343 18 509 214.049 +53 maps/rooms/64room_000.map 512 512 137 330 117 471 213.551 +53 maps/rooms/64room_000.map 512 512 331 63 437 195 212.811 +53 maps/rooms/64room_000.map 512 512 121 147 258 125 214.095 +53 maps/rooms/64room_000.map 512 512 42 299 229 346 215.095 +54 maps/rooms/64room_000.map 512 512 321 237 177 277 219.723 +54 maps/rooms/64room_000.map 512 512 324 317 260 135 219.38 +54 maps/rooms/64room_000.map 512 512 159 162 272 170 218.279 +54 maps/rooms/64room_000.map 512 512 445 300 323 191 217.125 +54 maps/rooms/64room_000.map 512 512 237 30 106 160 216.48 +54 maps/rooms/64room_000.map 512 512 138 237 66 124 216.983 +54 maps/rooms/64room_000.map 512 512 285 229 197 369 218.51 +54 maps/rooms/64room_000.map 512 512 156 17 185 148 217.581 +54 maps/rooms/64room_000.map 512 512 258 216 216 360 216.267 +54 maps/rooms/64room_000.map 512 512 182 108 52 230 217.421 +55 maps/rooms/64room_000.map 512 512 47 313 136 390 223.338 +55 maps/rooms/64room_000.map 512 512 179 168 143 51 221.125 +55 maps/rooms/64room_000.map 512 512 345 198 329 399 222.74 +55 maps/rooms/64room_000.map 512 512 404 345 301 387 221.51 +55 maps/rooms/64room_000.map 512 512 327 15 195 157 221.279 +55 maps/rooms/64room_000.map 512 512 186 495 104 371 222.794 +55 maps/rooms/64room_000.map 512 512 166 418 121 284 222.723 +55 maps/rooms/64room_000.map 512 512 230 328 300 281 222.238 +55 maps/rooms/64room_000.map 512 512 489 250 446 117 221.764 +55 maps/rooms/64room_000.map 512 512 225 116 410 60 220.095 +56 maps/rooms/64room_000.map 512 512 315 83 171 141 224.51 +56 maps/rooms/64room_000.map 512 512 429 22 309 112 227.966 +56 maps/rooms/64room_000.map 512 512 186 362 325 314 225.569 +56 maps/rooms/64room_000.map 512 512 115 491 248 375 224.48 +56 maps/rooms/64room_000.map 512 512 38 209 83 92 226.836 +56 maps/rooms/64room_000.map 512 512 110 260 131 87 224.794 +56 maps/rooms/64room_000.map 512 512 327 85 209 151 224.492 +56 maps/rooms/64room_000.map 512 512 338 248 397 444 225.267 +56 maps/rooms/64room_000.map 512 512 400 157 365 322 227.622 +56 maps/rooms/64room_000.map 512 512 54 232 153 362 226.907 +57 maps/rooms/64room_000.map 512 512 329 99 246 254 229.238 +57 maps/rooms/64room_000.map 512 512 113 83 101 295 231.054 +57 maps/rooms/64room_000.map 512 512 100 330 82 139 231.368 +57 maps/rooms/64room_000.map 512 512 317 294 486 251 228.451 +57 maps/rooms/64room_000.map 512 512 336 397 464 264 228.196 +57 maps/rooms/64room_000.map 512 512 380 507 464 339 231.095 +57 maps/rooms/64room_000.map 512 512 37 409 172 322 231.865 +57 maps/rooms/64room_000.map 512 512 443 370 372 234 231.794 +57 maps/rooms/64room_000.map 512 512 301 197 365 15 229.012 +57 maps/rooms/64room_000.map 512 512 199 57 395 52 229.551 +58 maps/rooms/64room_000.map 512 512 188 95 249 281 232.681 +58 maps/rooms/64room_000.map 512 512 165 119 114 293 232.865 +58 maps/rooms/64room_000.map 512 512 330 505 498 419 234.894 +58 maps/rooms/64room_000.map 512 512 197 117 340 233 235.995 +58 maps/rooms/64room_000.map 512 512 439 202 253 302 235.522 +58 maps/rooms/64room_000.map 512 512 142 401 71 394 235.581 +58 maps/rooms/64room_000.map 512 512 73 159 87 365 234.167 +58 maps/rooms/64room_000.map 512 512 198 94 78 30 234.309 +58 maps/rooms/64room_000.map 512 512 113 186 185 336 234.894 +58 maps/rooms/64room_000.map 512 512 227 153 69 271 234.309 +59 maps/rooms/64room_000.map 512 512 72 190 24 24 236.007 +59 maps/rooms/64room_000.map 512 512 317 221 329 435 237.296 +59 maps/rooms/64room_000.map 512 512 227 432 397 458 236.35 +59 maps/rooms/64room_000.map 512 512 115 308 275 310 237.522 +59 maps/rooms/64room_000.map 512 512 372 263 385 80 238.368 +59 maps/rooms/64room_000.map 512 512 124 109 287 58 239.522 +59 maps/rooms/64room_000.map 512 512 48 296 200 431 238.966 +59 maps/rooms/64room_000.map 512 512 362 385 253 255 237.066 +59 maps/rooms/64room_000.map 512 512 117 95 231 24 236.823 +59 maps/rooms/64room_000.map 512 512 137 8 235 196 236.794 +60 maps/rooms/64room_000.map 512 512 37 190 78 13 240.794 +60 maps/rooms/64room_000.map 512 512 489 465 415 501 243.823 +60 maps/rooms/64room_000.map 512 512 350 5 232 160 240.078 +60 maps/rooms/64room_000.map 512 512 257 233 163 62 243.409 +60 maps/rooms/64room_000.map 512 512 158 187 153 11 240.338 +60 maps/rooms/64room_000.map 512 512 35 272 162 398 240.179 +60 maps/rooms/64room_000.map 512 512 212 364 120 446 243.966 +60 maps/rooms/64room_000.map 512 512 210 288 7 361 242.024 +60 maps/rooms/64room_000.map 512 512 396 169 329 352 240.149 +60 maps/rooms/64room_000.map 512 512 55 106 174 214 241.995 +61 maps/rooms/64room_000.map 512 512 322 281 429 99 244.48 +61 maps/rooms/64room_000.map 512 512 93 328 310 263 245.095 +61 maps/rooms/64room_000.map 512 512 296 415 122 354 244.179 +61 maps/rooms/64room_000.map 512 512 6 221 174 138 245.794 +61 maps/rooms/64room_000.map 512 512 217 249 403 341 244.735 +61 maps/rooms/64room_000.map 512 512 252 150 390 134 247.321 +61 maps/rooms/64room_000.map 512 512 175 246 263 108 245.078 +61 maps/rooms/64room_000.map 512 512 346 359 435 175 245.35 +61 maps/rooms/64room_000.map 512 512 132 53 93 163 244.296 +61 maps/rooms/64room_000.map 512 512 211 404 375 496 247.238 +62 maps/rooms/64room_000.map 512 512 413 432 204 397 250.836 +62 maps/rooms/64room_000.map 512 512 29 258 156 122 248.865 +62 maps/rooms/64room_000.map 512 512 65 80 194 27 250.894 +62 maps/rooms/64room_000.map 512 512 214 274 424 329 251.794 +62 maps/rooms/64room_000.map 512 512 43 238 106 423 248.978 +62 maps/rooms/64room_000.map 512 512 110 288 303 272 251.551 +62 maps/rooms/64room_000.map 512 512 324 386 189 332 251.108 +62 maps/rooms/64room_000.map 512 512 396 459 194 409 250.794 +62 maps/rooms/64room_000.map 512 512 292 150 284 4 250.208 +62 maps/rooms/64room_000.map 512 512 307 217 93 283 248.309 +63 maps/rooms/64room_000.map 512 512 391 475 412 312 253.723 +63 maps/rooms/64room_000.map 512 512 310 153 228 48 252.907 +63 maps/rooms/64room_000.map 512 512 249 190 414 268 254.421 +63 maps/rooms/64room_000.map 512 512 17 262 167 164 253.321 +63 maps/rooms/64room_000.map 512 512 414 285 355 110 254.995 +63 maps/rooms/64room_000.map 512 512 380 222 394 422 254.794 +63 maps/rooms/64room_000.map 512 512 300 225 323 46 253.782 +63 maps/rooms/64room_000.map 512 512 263 133 413 286 253.877 +63 maps/rooms/64room_000.map 512 512 45 263 215 228 253.735 +63 maps/rooms/64room_000.map 512 512 137 337 269 177 252.752 +64 maps/rooms/64room_000.map 512 512 485 493 453 258 257.368 +64 maps/rooms/64room_000.map 512 512 39 283 115 483 258.777 +64 maps/rooms/64room_000.map 512 512 368 108 255 308 257.35 +64 maps/rooms/64room_000.map 512 512 182 334 394 277 257.953 +64 maps/rooms/64room_000.map 512 512 46 267 214 251 259.605 +64 maps/rooms/64room_000.map 512 512 237 295 112 156 257.907 +64 maps/rooms/64room_000.map 512 512 363 37 269 239 258.409 +64 maps/rooms/64room_000.map 512 512 243 378 44 273 258.894 +64 maps/rooms/64room_000.map 512 512 303 287 255 89 259.664 +64 maps/rooms/64room_000.map 512 512 166 28 378 23 259.635 +65 maps/rooms/64room_000.map 512 512 155 129 38 280 261.907 +65 maps/rooms/64room_000.map 512 512 174 114 330 107 262.706 +65 maps/rooms/64room_000.map 512 512 112 85 271 191 260.037 +65 maps/rooms/64room_000.map 512 512 375 166 422 344 263.995 +65 maps/rooms/64room_000.map 512 512 499 127 286 137 260.279 +65 maps/rooms/64room_000.map 512 512 75 173 298 219 260.924 +65 maps/rooms/64room_000.map 512 512 509 165 301 210 262.522 +65 maps/rooms/64room_000.map 512 512 150 209 209 415 262.095 +65 maps/rooms/64room_000.map 512 512 188 133 129 283 262.095 +65 maps/rooms/64room_000.map 512 512 296 140 156 33 262.12 +66 maps/rooms/64room_000.map 512 512 357 353 195 422 266.706 +66 maps/rooms/64room_000.map 512 512 122 298 327 236 265.368 +66 maps/rooms/64room_000.map 512 512 213 459 350 378 265.304 +66 maps/rooms/64room_000.map 512 512 109 508 102 295 266.049 +66 maps/rooms/64room_000.map 512 512 223 89 412 147 267.451 +66 maps/rooms/64room_000.map 512 512 203 273 430 260 266.35 +66 maps/rooms/64room_000.map 512 512 326 424 349 181 264.125 +66 maps/rooms/64room_000.map 512 512 196 403 49 362 267.622 +66 maps/rooms/64room_000.map 512 512 32 43 213 107 266.279 +66 maps/rooms/64room_000.map 512 512 142 145 195 263 267.61 +67 maps/rooms/64room_000.map 512 512 207 61 245 288 269.066 +67 maps/rooms/64room_000.map 512 512 445 2 250 60 269.25 +67 maps/rooms/64room_000.map 512 512 220 301 264 95 268.167 +67 maps/rooms/64room_000.map 512 512 264 271 281 414 271.037 +67 maps/rooms/64room_000.map 512 512 409 306 244 152 268.037 +67 maps/rooms/64room_000.map 512 512 114 252 231 89 270.291 +67 maps/rooms/64room_000.map 512 512 446 42 317 241 270.836 +67 maps/rooms/64room_000.map 512 512 217 481 263 293 270.953 +67 maps/rooms/64room_000.map 512 512 66 188 49 172 270.463 +67 maps/rooms/64room_000.map 512 512 78 257 311 316 269.037 +68 maps/rooms/64room_000.map 512 512 217 445 108 243 275.451 +68 maps/rooms/64room_000.map 512 512 199 308 403 184 275.563 +68 maps/rooms/64room_000.map 512 512 274 281 404 77 274.836 +68 maps/rooms/64room_000.map 512 512 261 197 277 116 273.593 +68 maps/rooms/64room_000.map 512 512 390 38 182 29 274.966 +68 maps/rooms/64room_000.map 512 512 220 338 96 189 274.179 +68 maps/rooms/64room_000.map 512 512 181 247 67 416 272.362 +68 maps/rooms/64room_000.map 512 512 28 407 152 296 272.103 +68 maps/rooms/64room_000.map 512 512 109 259 346 274 275.581 +68 maps/rooms/64room_000.map 512 512 110 209 163 418 273.622 +69 maps/rooms/64room_000.map 512 512 232 58 153 238 279.208 +69 maps/rooms/64room_000.map 512 512 381 252 509 337 278.924 +69 maps/rooms/64room_000.map 512 512 262 135 166 357 278.752 +69 maps/rooms/64room_000.map 512 512 292 168 476 265 278.563 +69 maps/rooms/64room_000.map 512 512 26 198 239 271 277.463 +69 maps/rooms/64room_000.map 512 512 35 89 267 83 279.907 +69 maps/rooms/64room_000.map 512 512 162 315 411 317 276.338 +69 maps/rooms/64room_000.map 512 512 167 52 389 30 279.238 +69 maps/rooms/64room_000.map 512 512 294 202 177 139 279.279 +69 maps/rooms/64room_000.map 512 512 323 166 387 396 279.539 +70 maps/rooms/64room_000.map 512 512 297 240 163 47 283.652 +70 maps/rooms/64room_000.map 512 512 201 281 378 394 280.309 +70 maps/rooms/64room_000.map 512 512 378 239 298 29 282.451 +70 maps/rooms/64room_000.map 512 512 137 438 180 207 281.12 +70 maps/rooms/64room_000.map 512 512 510 340 413 495 280.35 +70 maps/rooms/64room_000.map 512 512 426 357 201 269 280.463 +70 maps/rooms/64room_000.map 512 512 105 310 305 166 280.149 +70 maps/rooms/64room_000.map 512 512 344 231 117 232 283.581 +70 maps/rooms/64room_000.map 512 512 191 436 351 352 280.291 +70 maps/rooms/64room_000.map 512 512 198 163 413 109 282.161 +71 maps/rooms/64room_000.map 512 512 307 119 285 242 287.534 +71 maps/rooms/64room_000.map 512 512 210 257 133 178 286.853 +71 maps/rooms/64room_000.map 512 512 118 78 226 229 285.995 +71 maps/rooms/64room_000.map 512 512 289 304 14 314 287.284 +71 maps/rooms/64room_000.map 512 512 68 220 312 197 286.664 +71 maps/rooms/64room_000.map 512 512 197 415 422 494 285.806 +71 maps/rooms/64room_000.map 512 512 11 36 221 109 285.593 +71 maps/rooms/64room_000.map 512 512 33 286 167 171 285.676 +71 maps/rooms/64room_000.map 512 512 62 358 213 473 287.279 +71 maps/rooms/64room_000.map 512 512 272 165 58 312 284.546 +72 maps/rooms/64room_000.map 512 512 505 185 406 295 289.735 +72 maps/rooms/64room_000.map 512 512 141 261 332 336 290.777 +72 maps/rooms/64room_000.map 512 512 152 449 74 279 289.321 +72 maps/rooms/64room_000.map 512 512 216 101 91 306 290.978 +72 maps/rooms/64room_000.map 512 512 382 122 386 323 288.154 +72 maps/rooms/64room_000.map 512 512 431 67 310 272 289.806 +72 maps/rooms/64room_000.map 512 512 494 426 302 273 289.35 +72 maps/rooms/64room_000.map 512 512 396 267 492 196 289.635 +72 maps/rooms/64room_000.map 512 512 406 73 174 90 289.392 +72 maps/rooms/64room_000.map 512 512 221 143 227 333 288.066 +73 maps/rooms/64room_000.map 512 512 498 182 353 348 294.865 +73 maps/rooms/64room_000.map 512 512 365 359 207 144 292.747 +73 maps/rooms/64room_000.map 512 512 247 259 139 499 295.806 +73 maps/rooms/64room_000.map 512 512 367 419 432 208 293.723 +73 maps/rooms/64room_000.map 512 512 324 314 148 410 293.681 +73 maps/rooms/64room_000.map 512 512 147 94 189 264 292.894 +73 maps/rooms/64room_000.map 512 512 434 271 216 171 295.362 +73 maps/rooms/64room_000.map 512 512 149 316 8 439 293.924 +73 maps/rooms/64room_000.map 512 512 437 65 207 205 295.019 +73 maps/rooms/64room_000.map 512 512 133 424 8 278 293.919 +74 maps/rooms/64room_000.map 512 512 61 225 186 58 298.108 +74 maps/rooms/64room_000.map 512 512 308 247 127 174 298.409 +74 maps/rooms/64room_000.map 512 512 13 298 268 392 296.279 +74 maps/rooms/64room_000.map 512 512 39 326 291 235 298.664 +74 maps/rooms/64room_000.map 512 512 335 283 455 65 296.995 +74 maps/rooms/64room_000.map 512 512 194 40 116 252 297.179 +74 maps/rooms/64room_000.map 512 512 87 120 46 353 296.25 +74 maps/rooms/64room_000.map 512 512 166 344 335 166 296.806 +74 maps/rooms/64room_000.map 512 512 372 335 385 83 296.48 +74 maps/rooms/64room_000.map 512 512 197 200 450 290 296.421 +75 maps/rooms/64room_000.map 512 512 319 100 501 75 301.978 +75 maps/rooms/64room_000.map 512 512 400 317 447 455 300.966 +75 maps/rooms/64room_000.map 512 512 319 57 316 288 301.196 +75 maps/rooms/64room_000.map 512 512 94 259 359 275 300.48 +75 maps/rooms/64room_000.map 512 512 297 406 189 219 300.563 +75 maps/rooms/64room_000.map 512 512 241 186 52 381 302.576 +75 maps/rooms/64room_000.map 512 512 142 163 369 36 300.108 +75 maps/rooms/64room_000.map 512 512 130 280 75 488 303.635 +75 maps/rooms/64room_000.map 512 512 291 442 170 232 300.747 +75 maps/rooms/64room_000.map 512 512 316 248 471 424 302.865 +76 maps/rooms/64room_000.map 512 512 201 181 428 40 306.978 +76 maps/rooms/64room_000.map 512 512 306 399 151 206 304.936 +76 maps/rooms/64room_000.map 512 512 405 415 206 310 305.137 +76 maps/rooms/64room_000.map 512 512 168 324 435 324 307.894 +76 maps/rooms/64room_000.map 512 512 109 451 72 226 304.049 +76 maps/rooms/64room_000.map 512 512 194 501 106 312 306.137 +76 maps/rooms/64room_000.map 512 512 158 265 265 116 304.191 +76 maps/rooms/64room_000.map 512 512 38 399 194 324 307.534 +76 maps/rooms/64room_000.map 512 512 66 379 286 240 305.978 +76 maps/rooms/64room_000.map 512 512 159 456 37 291 306.99 +77 maps/rooms/64room_000.map 512 512 201 335 21 478 309.576 +77 maps/rooms/64room_000.map 512 512 270 445 190 249 308.007 +77 maps/rooms/64room_000.map 512 512 196 28 65 20 310.723 +77 maps/rooms/64room_000.map 512 512 271 232 5 199 308.522 +77 maps/rooms/64room_000.map 512 512 65 282 61 33 309.877 +77 maps/rooms/64room_000.map 512 512 284 432 84 280 311.907 +77 maps/rooms/64room_000.map 512 512 108 9 203 56 308.978 +77 maps/rooms/64room_000.map 512 512 221 27 297 271 308.978 +77 maps/rooms/64room_000.map 512 512 37 154 232 111 308.208 +77 maps/rooms/64room_000.map 512 512 40 113 13 292 310.894 +78 maps/rooms/64room_000.map 512 512 277 245 482 72 315.321 +78 maps/rooms/64room_000.map 512 512 24 232 41 475 313.002 +78 maps/rooms/64room_000.map 512 512 249 144 45 8 314.534 +78 maps/rooms/64room_000.map 512 512 37 81 296 88 315.806 +78 maps/rooms/64room_000.map 512 512 117 481 253 283 314.25 +78 maps/rooms/64room_000.map 512 512 238 336 290 173 314.966 +78 maps/rooms/64room_000.map 512 512 204 231 90 56 313.392 +78 maps/rooms/64room_000.map 512 512 341 52 83 98 312.877 +78 maps/rooms/64room_000.map 512 512 365 315 204 439 313.09 +78 maps/rooms/64room_000.map 512 512 158 111 92 363 314.191 +79 maps/rooms/64room_000.map 512 512 339 2 464 11 316.475 +79 maps/rooms/64room_000.map 512 512 65 175 315 27 316.576 +79 maps/rooms/64room_000.map 512 512 126 376 121 112 319.09 +79 maps/rooms/64room_000.map 512 512 4 86 230 187 317.35 +79 maps/rooms/64room_000.map 512 512 493 340 359 162 319.865 +79 maps/rooms/64room_000.map 512 512 171 248 171 492 318.919 +79 maps/rooms/64room_000.map 512 512 133 6 183 200 316.777 +79 maps/rooms/64room_000.map 512 512 110 118 312 241 319.451 +79 maps/rooms/64room_000.map 512 512 287 138 462 322 317.108 +79 maps/rooms/64room_000.map 512 512 442 396 189 437 318.576 +80 maps/rooms/64room_000.map 512 512 154 57 5 89 322.238 +80 maps/rooms/64room_000.map 512 512 443 418 182 410 321.191 +80 maps/rooms/64room_000.map 512 512 303 74 380 247 322.451 +80 maps/rooms/64room_000.map 512 512 220 290 310 26 320.836 +80 maps/rooms/64room_000.map 512 512 332 511 181 349 323.233 +80 maps/rooms/64room_000.map 512 512 63 308 161 66 322.877 +80 maps/rooms/64room_000.map 512 512 463 86 348 318 320.865 +80 maps/rooms/64room_000.map 512 512 154 262 237 30 323.919 +80 maps/rooms/64room_000.map 512 512 224 65 498 125 322.735 +80 maps/rooms/64room_000.map 512 512 306 172 122 65 320.421 +81 maps/rooms/64room_000.map 512 512 212 163 478 178 327.718 +81 maps/rooms/64room_000.map 512 512 383 433 387 184 324.463 +81 maps/rooms/64room_000.map 512 512 131 352 100 120 326.137 +81 maps/rooms/64room_000.map 512 512 120 263 374 99 325.446 +81 maps/rooms/64room_000.map 512 512 466 188 179 242 324.723 +81 maps/rooms/64room_000.map 512 512 140 43 409 110 325.12 +81 maps/rooms/64room_000.map 512 512 5 33 112 261 324.22 +81 maps/rooms/64room_000.map 512 512 321 194 185 421 327.167 +81 maps/rooms/64room_000.map 512 512 130 138 305 303 327.664 +81 maps/rooms/64room_000.map 512 512 247 282 229 2 327.907 +82 maps/rooms/64room_000.map 512 512 237 295 142 25 331.936 +82 maps/rooms/64room_000.map 512 512 206 300 141 37 330.066 +82 maps/rooms/64room_000.map 512 512 510 298 199 298 330.882 +82 maps/rooms/64room_000.map 512 512 158 49 335 255 328.522 +82 maps/rooms/64room_000.map 512 512 275 161 50 73 330.362 +82 maps/rooms/64room_000.map 512 512 486 280 258 434 328.777 +82 maps/rooms/64room_000.map 512 512 66 332 354 254 331.439 +82 maps/rooms/64room_000.map 512 512 104 104 105 387 328.978 +82 maps/rooms/64room_000.map 512 512 311 301 463 452 329.149 +82 maps/rooms/64room_000.map 512 512 99 241 161 486 329.919 +83 maps/rooms/64room_000.map 512 512 500 197 405 342 332.836 +83 maps/rooms/64room_000.map 512 512 134 499 294 267 334.492 +83 maps/rooms/64room_000.map 512 512 183 378 244 85 332.652 +83 maps/rooms/64room_000.map 512 512 232 287 506 210 334.706 +83 maps/rooms/64room_000.map 512 512 382 303 254 325 334.451 +83 maps/rooms/64room_000.map 512 512 111 139 331 174 332.747 +83 maps/rooms/64room_000.map 512 512 463 458 312 302 332.22 +83 maps/rooms/64room_000.map 512 512 73 201 28 457 334.99 +83 maps/rooms/64room_000.map 512 512 91 2 223 181 332.078 +83 maps/rooms/64room_000.map 512 512 242 359 510 435 332.978 +84 maps/rooms/64room_000.map 512 512 126 288 348 348 337.948 +84 maps/rooms/64room_000.map 512 512 129 268 287 30 337.161 +84 maps/rooms/64room_000.map 512 512 211 151 46 379 336.446 +84 maps/rooms/64room_000.map 512 512 57 215 237 418 336.12 +84 maps/rooms/64room_000.map 512 512 434 207 301 125 339.108 +84 maps/rooms/64room_000.map 512 512 440 171 509 282 338.919 +84 maps/rooms/64room_000.map 512 512 456 331 447 148 338.96 +84 maps/rooms/64room_000.map 512 512 460 336 176 231 339.007 +84 maps/rooms/64room_000.map 512 512 248 19 95 252 337.706 +84 maps/rooms/64room_000.map 512 512 303 222 8 266 339.066 +85 maps/rooms/64room_000.map 512 512 52 56 283 70 342.262 +85 maps/rooms/64room_000.map 512 512 162 200 425 371 343.203 +85 maps/rooms/64room_000.map 512 512 507 253 401 351 342.392 +85 maps/rooms/64room_000.map 512 512 161 338 441 465 341.978 +85 maps/rooms/64room_000.map 512 512 282 285 486 472 342.907 +85 maps/rooms/64room_000.map 512 512 114 11 181 26 341.12 +85 maps/rooms/64room_000.map 512 512 165 221 446 351 343.049 +85 maps/rooms/64room_000.map 512 512 226 88 203 321 342.652 +85 maps/rooms/64room_000.map 512 512 176 119 201 381 340.966 +85 maps/rooms/64room_000.map 512 512 71 227 56 510 340.676 +86 maps/rooms/64room_000.map 512 512 161 204 408 117 345.144 +86 maps/rooms/64room_000.map 512 512 251 415 225 141 345.723 +86 maps/rooms/64room_000.map 512 512 193 134 134 398 346.037 +86 maps/rooms/64room_000.map 512 512 347 507 150 443 346.99 +86 maps/rooms/64room_000.map 512 512 471 328 254 432 347.333 +86 maps/rooms/64room_000.map 512 512 161 36 177 278 346.333 +86 maps/rooms/64room_000.map 512 512 332 243 92 125 347.764 +86 maps/rooms/64room_000.map 512 512 132 275 380 416 347.174 +86 maps/rooms/64room_000.map 512 512 92 508 23 227 344.718 +86 maps/rooms/64room_000.map 512 512 404 304 464 83 345.191 +87 maps/rooms/64room_000.map 512 512 254 487 16 343 351.019 +87 maps/rooms/64room_000.map 512 512 440 293 236 401 349.463 +87 maps/rooms/64room_000.map 512 512 231 47 345 274 348.22 +87 maps/rooms/64room_000.map 512 512 287 269 157 511 351.12 +87 maps/rooms/64room_000.map 512 512 509 300 259 139 349.191 +87 maps/rooms/64room_000.map 512 512 467 319 241 146 350.078 +87 maps/rooms/64room_000.map 512 512 310 237 56 382 350.966 +87 maps/rooms/64room_000.map 512 512 341 191 475 438 348.38 +87 maps/rooms/64room_000.map 512 512 242 34 479 208 348.061 +87 maps/rooms/64room_000.map 512 512 24 299 261 132 351.789 +88 maps/rooms/64room_000.map 512 512 226 99 188 419 354.267 +88 maps/rooms/64room_000.map 512 512 399 231 259 440 355.593 +88 maps/rooms/64room_000.map 512 512 175 56 460 127 353.463 +88 maps/rooms/64room_000.map 512 512 132 503 61 244 353.203 +88 maps/rooms/64room_000.map 512 512 138 93 433 106 353.262 +88 maps/rooms/64room_000.map 512 512 479 234 492 309 352.291 +88 maps/rooms/64room_000.map 512 512 393 193 101 223 355.321 +88 maps/rooms/64room_000.map 512 512 292 241 496 467 355.019 +88 maps/rooms/64room_000.map 512 512 236 150 500 69 352.203 +88 maps/rooms/64room_000.map 512 512 135 428 249 132 352.836 +89 maps/rooms/64room_000.map 512 512 465 40 279 176 358.718 +89 maps/rooms/64room_000.map 512 512 314 190 502 386 357.882 +89 maps/rooms/64room_000.map 512 512 252 296 317 12 356.99 +89 maps/rooms/64room_000.map 512 512 341 312 198 27 359.848 +89 maps/rooms/64room_000.map 512 512 150 282 466 306 357.421 +89 maps/rooms/64room_000.map 512 512 109 389 142 96 358.676 +89 maps/rooms/64room_000.map 512 512 206 363 430 202 359.534 +89 maps/rooms/64room_000.map 512 512 378 335 185 86 358.233 +89 maps/rooms/64room_000.map 512 512 262 83 351 346 358.375 +89 maps/rooms/64room_000.map 512 512 381 115 328 427 359.024 +90 maps/rooms/64room_000.map 512 512 242 499 30 380 360.546 +90 maps/rooms/64room_000.map 512 512 65 250 361 185 360.48 +90 maps/rooms/64room_000.map 512 512 375 242 158 56 362.723 +90 maps/rooms/64room_000.map 512 512 13 77 272 21 363.534 +90 maps/rooms/64room_000.map 512 512 175 86 425 206 363.772 +90 maps/rooms/64room_000.map 512 512 371 355 77 313 363.037 +90 maps/rooms/64room_000.map 512 512 101 45 191 271 360.049 +90 maps/rooms/64room_000.map 512 512 199 328 127 102 363.605 +90 maps/rooms/64room_000.map 512 512 284 397 359 172 362.836 +90 maps/rooms/64room_000.map 512 512 208 111 26 353 363.487 +91 maps/rooms/64room_000.map 512 512 249 294 331 18 366.919 +91 maps/rooms/64room_000.map 512 512 502 61 224 183 366.818 +91 maps/rooms/64room_000.map 512 512 148 486 289 220 364.019 +91 maps/rooms/64room_000.map 512 512 479 149 406 381 367.919 +91 maps/rooms/64room_000.map 512 512 269 98 41 129 364.078 +91 maps/rooms/64room_000.map 512 512 6 510 232 362 366.375 +91 maps/rooms/64room_000.map 512 512 224 2 419 240 367.392 +91 maps/rooms/64room_000.map 512 512 298 177 84 27 364.919 +91 maps/rooms/64room_000.map 512 512 99 98 7 392 365.789 +91 maps/rooms/64room_000.map 512 512 469 181 213 41 365.889 +92 maps/rooms/64room_000.map 512 512 440 279 335 47 371.25 +92 maps/rooms/64room_000.map 512 512 327 60 364 368 368.681 +92 maps/rooms/64room_000.map 512 512 308 48 87 19 370.475 +92 maps/rooms/64room_000.map 512 512 312 446 447 157 369.99 +92 maps/rooms/64room_000.map 512 512 201 200 510 139 370.233 +92 maps/rooms/64room_000.map 512 512 186 477 243 197 368.262 +92 maps/rooms/64room_000.map 512 512 68 110 281 269 370.434 +92 maps/rooms/64room_000.map 512 512 90 291 169 17 368.22 +92 maps/rooms/64room_000.map 512 512 334 263 116 103 368.978 +92 maps/rooms/64room_000.map 512 512 146 304 484 306 370.309 +93 maps/rooms/64room_000.map 512 512 369 407 123 272 373.701 +93 maps/rooms/64room_000.map 512 512 498 148 198 312 375.546 +93 maps/rooms/64room_000.map 512 512 319 194 15 109 372.907 +93 maps/rooms/64room_000.map 512 512 117 307 390 313 373.877 +93 maps/rooms/64room_000.map 512 512 109 227 406 255 375.392 +93 maps/rooms/64room_000.map 512 512 450 486 284 279 375.818 +93 maps/rooms/64room_000.map 512 512 190 100 254 362 372.894 +93 maps/rooms/64room_000.map 512 512 414 257 424 55 373.161 +93 maps/rooms/64room_000.map 512 512 96 68 6 373 373.475 +93 maps/rooms/64room_000.map 512 512 154 188 105 397 372.233 +94 maps/rooms/64room_000.map 512 512 60 323 409 288 378.267 +94 maps/rooms/64room_000.map 512 512 434 361 480 139 379.889 +94 maps/rooms/64room_000.map 512 512 230 296 493 445 376.534 +94 maps/rooms/64room_000.map 512 512 447 50 157 208 379.387 +94 maps/rooms/64room_000.map 512 512 235 329 97 111 377.889 +94 maps/rooms/64room_000.map 512 512 61 66 104 361 378.877 +94 maps/rooms/64room_000.map 512 512 443 190 376 476 376.563 +94 maps/rooms/64room_000.map 512 512 335 358 82 281 376.86 +94 maps/rooms/64room_000.map 512 512 445 414 182 284 379.191 +94 maps/rooms/64room_000.map 512 512 207 212 118 7 376.274 +95 maps/rooms/64room_000.map 512 512 368 8 394 322 383.681 +95 maps/rooms/64room_000.map 512 512 121 38 190 268 380.706 +95 maps/rooms/64room_000.map 512 512 477 136 192 318 383.818 +95 maps/rooms/64room_000.map 512 512 375 347 66 289 381.936 +95 maps/rooms/64room_000.map 512 512 321 359 120 306 380.617 +95 maps/rooms/64room_000.map 512 512 114 159 399 122 381.505 +95 maps/rooms/64room_000.map 512 512 385 125 331 444 380.581 +95 maps/rooms/64room_000.map 512 512 385 425 190 462 380.718 +95 maps/rooms/64room_000.map 512 512 354 370 156 126 383.99 +95 maps/rooms/64room_000.map 512 512 473 476 209 428 382.174 +96 maps/rooms/64room_000.map 512 512 325 432 329 73 386.338 +96 maps/rooms/64room_000.map 512 512 18 506 156 218 385.487 +96 maps/rooms/64room_000.map 512 512 124 188 117 459 386.635 +96 maps/rooms/64room_000.map 512 512 47 412 242 196 384.085 +96 maps/rooms/64room_000.map 512 512 473 12 251 36 385.304 +96 maps/rooms/64room_000.map 512 512 291 404 443 207 387.877 +96 maps/rooms/64room_000.map 512 512 97 333 363 144 384.706 +96 maps/rooms/64room_000.map 512 512 187 373 488 393 386.588 +96 maps/rooms/64room_000.map 512 512 489 472 353 203 386.907 +96 maps/rooms/64room_000.map 512 512 498 285 334 65 385.238 +97 maps/rooms/64room_000.map 512 512 65 139 379 106 390.907 +97 maps/rooms/64room_000.map 512 512 82 92 289 318 390.588 +97 maps/rooms/64room_000.map 512 512 57 477 199 194 390.931 +97 maps/rooms/64room_000.map 512 512 463 495 232 354 390.517 +97 maps/rooms/64room_000.map 512 512 237 372 261 89 390.22 +97 maps/rooms/64room_000.map 512 512 3 53 48 305 389.274 +97 maps/rooms/64room_000.map 512 512 232 74 409 345 389.304 +97 maps/rooms/64room_000.map 512 512 35 393 259 213 391.103 +97 maps/rooms/64room_000.map 512 512 124 309 151 24 391.848 +97 maps/rooms/64room_000.map 512 512 99 461 304 248 391.948 +98 maps/rooms/64room_000.map 512 512 389 19 424 257 392.22 +98 maps/rooms/64room_000.map 512 512 415 242 497 409 392.22 +98 maps/rooms/64room_000.map 512 512 81 205 327 432 395.073 +98 maps/rooms/64room_000.map 512 512 470 59 242 121 393.463 +98 maps/rooms/64room_000.map 512 512 378 359 306 39 395.764 +98 maps/rooms/64room_000.map 512 512 176 50 210 332 394.836 +98 maps/rooms/64room_000.map 512 512 107 151 432 116 395.203 +98 maps/rooms/64room_000.map 512 512 294 41 404 262 394.563 +98 maps/rooms/64room_000.map 512 512 363 367 504 89 394.203 +98 maps/rooms/64room_000.map 512 512 352 188 224 416 395.563 +99 maps/rooms/64room_000.map 512 512 357 26 28 89 398.375 +99 maps/rooms/64room_000.map 512 512 172 411 121 93 396.706 +99 maps/rooms/64room_000.map 512 512 132 282 461 252 398.664 +99 maps/rooms/64room_000.map 512 512 84 449 125 122 398.919 +99 maps/rooms/64room_000.map 512 512 407 352 161 118 396.032 +99 maps/rooms/64room_000.map 512 512 434 417 322 101 397.865 +99 maps/rooms/64room_000.map 512 512 203 475 376 238 398.451 +99 maps/rooms/64room_000.map 512 512 189 271 23 29 397.806 +99 maps/rooms/64room_000.map 512 512 430 221 259 405 396.948 +99 maps/rooms/64room_000.map 512 512 166 355 239 22 399.848 +100 maps/rooms/64room_000.map 512 512 4 161 81 339 402.563 +100 maps/rooms/64room_000.map 512 512 112 389 314 130 403.777 +100 maps/rooms/64room_000.map 512 512 430 276 153 434 401.35 +100 maps/rooms/64room_000.map 512 512 451 375 454 151 403.936 +100 maps/rooms/64room_000.map 512 512 300 432 13 443 403.789 +100 maps/rooms/64room_000.map 512 512 201 73 185 438 401.752 +100 maps/rooms/64room_000.map 512 512 310 245 59 454 401.161 +100 maps/rooms/64room_000.map 512 512 419 335 326 33 403.451 +100 maps/rooms/64room_000.map 512 512 127 316 418 273 402.191 +100 maps/rooms/64room_000.map 512 512 207 351 501 273 402.309 +101 maps/rooms/64room_000.map 512 512 41 191 132 281 405.635 +101 maps/rooms/64room_000.map 512 512 133 170 400 150 404.286 +101 maps/rooms/64room_000.map 512 512 98 154 19 484 406.931 +101 maps/rooms/64room_000.map 512 512 225 152 20 424 404.671 +101 maps/rooms/64room_000.map 512 512 333 158 205 411 407.877 +101 maps/rooms/64room_000.map 512 512 509 350 199 162 406.032 +101 maps/rooms/64room_000.map 512 512 99 218 417 362 406.316 +101 maps/rooms/64room_000.map 512 512 25 171 298 51 405.818 +101 maps/rooms/64room_000.map 512 512 355 402 41 291 404.73 +101 maps/rooms/64room_000.map 512 512 193 86 346 413 405.161 +102 maps/rooms/64room_000.map 512 512 65 14 279 223 410.747 +102 maps/rooms/64room_000.map 512 512 404 331 304 33 411.723 +102 maps/rooms/64room_000.map 512 512 58 177 179 9 411.291 +102 maps/rooms/64room_000.map 512 512 202 124 394 432 409.789 +102 maps/rooms/64room_000.map 512 512 308 63 15 3 408.446 +102 maps/rooms/64room_000.map 512 512 238 252 29 52 409.132 +102 maps/rooms/64room_000.map 512 512 141 95 90 437 411.233 +102 maps/rooms/64room_000.map 512 512 97 326 437 407 409.517 +102 maps/rooms/64room_000.map 512 512 389 223 194 389 410.078 +102 maps/rooms/64room_000.map 512 512 421 327 71 258 411.676 +103 maps/rooms/64room_000.map 512 512 246 350 171 176 414.345 +103 maps/rooms/64room_000.map 512 512 440 262 137 410 412.664 +103 maps/rooms/64room_000.map 512 512 185 11 142 363 412.706 +103 maps/rooms/64room_000.map 512 512 500 503 326 203 415.421 +103 maps/rooms/64room_000.map 512 512 27 13 57 347 415.789 +103 maps/rooms/64room_000.map 512 512 395 356 141 486 415.789 +103 maps/rooms/64room_000.map 512 512 450 185 312 390 413.392 +103 maps/rooms/64room_000.map 512 512 229 123 149 470 412.706 +103 maps/rooms/64room_000.map 512 512 150 165 40 426 413.985 +103 maps/rooms/64room_000.map 512 512 457 219 83 251 415.279 +104 maps/rooms/64room_000.map 512 512 430 125 180 182 417.316 +104 maps/rooms/64room_000.map 512 512 490 421 198 206 419.132 +104 maps/rooms/64room_000.map 512 512 151 304 54 142 416.321 +104 maps/rooms/64room_000.map 512 512 444 127 189 147 416.103 +104 maps/rooms/64room_000.map 512 512 72 80 378 111 416.286 +104 maps/rooms/64room_000.map 512 512 223 257 506 439 416.061 +104 maps/rooms/64room_000.map 512 512 114 353 126 48 417.032 +104 maps/rooms/64room_000.map 512 512 101 323 10 167 418.563 +104 maps/rooms/64room_000.map 512 512 34 14 324 38 418.274 +104 maps/rooms/64room_000.map 512 512 174 82 131 398 417.108 +105 maps/rooms/64room_000.map 512 512 63 100 381 111 422.019 +105 maps/rooms/64room_000.map 512 512 177 18 349 356 422.718 +105 maps/rooms/64room_000.map 512 512 206 325 451 202 421.362 +105 maps/rooms/64room_000.map 512 512 397 313 224 486 420.6 +105 maps/rooms/64room_000.map 512 512 54 108 235 382 421.96 +105 maps/rooms/64room_000.map 512 512 185 97 436 372 420.558 +105 maps/rooms/64room_000.map 512 512 198 449 505 498 421.73 +105 maps/rooms/64room_000.map 512 512 6 335 118 48 422.304 +105 maps/rooms/64room_000.map 512 512 101 432 316 156 422.463 +105 maps/rooms/64room_000.map 512 512 118 330 92 2 421.161 +106 maps/rooms/64room_000.map 512 512 16 110 275 304 426.404 +106 maps/rooms/64room_000.map 512 512 18 213 364 143 426.558 +106 maps/rooms/64room_000.map 512 512 15 144 179 335 424.647 +106 maps/rooms/64room_000.map 512 512 50 187 246 210 424.889 +106 maps/rooms/64room_000.map 512 512 191 205 366 504 427.948 +106 maps/rooms/64room_000.map 512 512 126 100 394 153 427.257 +106 maps/rooms/64room_000.map 512 512 397 289 145 58 424.99 +106 maps/rooms/64room_000.map 512 512 470 335 353 37 427.25 +106 maps/rooms/64room_000.map 512 512 350 503 97 360 424.801 +106 maps/rooms/64room_000.map 512 512 162 183 250 373 425.245 +107 maps/rooms/64room_000.map 512 512 362 33 120 304 429.375 +107 maps/rooms/64room_000.map 512 512 62 325 151 18 430.96 +107 maps/rooms/64room_000.map 512 512 507 354 409 106 431.019 +107 maps/rooms/64room_000.map 512 512 335 416 468 82 431.735 +107 maps/rooms/64room_000.map 512 512 380 316 249 8 428.12 +107 maps/rooms/64room_000.map 512 512 138 132 294 390 429.688 +107 maps/rooms/64room_000.map 512 512 366 34 60 49 431.032 +107 maps/rooms/64room_000.map 512 512 413 86 170 358 429.475 +107 maps/rooms/64room_000.map 512 512 138 61 41 276 428.777 +107 maps/rooms/64room_000.map 512 512 382 429 124 223 431.872 +108 maps/rooms/64room_000.map 512 512 393 372 141 101 433.96 +108 maps/rooms/64room_000.map 512 512 129 1 193 356 433.09 +108 maps/rooms/64room_000.map 512 512 68 305 374 502 434.505 +108 maps/rooms/64room_000.map 512 512 321 383 50 360 434.149 +108 maps/rooms/64room_000.map 512 512 68 398 391 225 434.09 +108 maps/rooms/64room_000.map 512 512 395 72 83 60 434.174 +108 maps/rooms/64room_000.map 512 512 420 140 278 392 434.617 +108 maps/rooms/64room_000.map 512 512 219 466 453 290 434.156 +108 maps/rooms/64room_000.map 512 512 374 337 118 114 435.073 +108 maps/rooms/64room_000.map 512 512 147 251 482 65 432.328 +109 maps/rooms/64room_000.map 512 512 97 321 140 60 438.049 +109 maps/rooms/64room_000.map 512 512 247 262 34 151 438.818 +109 maps/rooms/64room_000.map 512 512 172 101 56 443 438.357 +109 maps/rooms/64room_000.map 512 512 334 94 81 353 436.014 +109 maps/rooms/64room_000.map 512 512 123 213 498 253 436.806 +109 maps/rooms/64room_000.map 512 512 139 287 451 131 439.421 +109 maps/rooms/64room_000.map 512 512 419 349 150 137 438.002 +109 maps/rooms/64room_000.map 512 512 505 397 264 136 439.321 +109 maps/rooms/64room_000.map 512 512 382 423 327 46 436.936 +109 maps/rooms/64room_000.map 512 512 440 16 406 349 437.534 +110 maps/rooms/64room_000.map 512 512 202 442 402 156 442.576 +110 maps/rooms/64room_000.map 512 512 232 479 116 130 443.475 +110 maps/rooms/64room_000.map 512 512 53 329 258 45 441.742 +110 maps/rooms/64room_000.map 512 512 369 335 164 191 442.002 +110 maps/rooms/64room_000.map 512 512 473 110 130 180 443.818 +110 maps/rooms/64room_000.map 512 512 58 93 3 428 442.617 +110 maps/rooms/64room_000.map 512 512 126 134 311 406 442.002 +110 maps/rooms/64room_000.map 512 512 483 302 165 426 440.551 +110 maps/rooms/64room_000.map 512 512 262 219 468 509 440.558 +110 maps/rooms/64room_000.map 512 512 138 316 496 140 442.517 +111 maps/rooms/64room_000.map 512 512 477 13 397 284 444.571 +111 maps/rooms/64room_000.map 512 512 437 218 71 382 445.304 +111 maps/rooms/64room_000.map 512 512 350 103 21 95 444.002 +111 maps/rooms/64room_000.map 512 512 155 370 454 135 447.304 +111 maps/rooms/64room_000.map 512 512 281 83 379 387 446.375 +111 maps/rooms/64room_000.map 512 512 97 382 19 48 444.174 +111 maps/rooms/64room_000.map 512 512 437 351 163 461 444.558 +111 maps/rooms/64room_000.map 512 512 499 490 250 202 446.789 +111 maps/rooms/64room_000.map 512 512 357 343 464 45 446.931 +111 maps/rooms/64room_000.map 512 512 103 47 328 168 445.772 +112 maps/rooms/64room_000.map 512 512 375 327 8 206 448.902 +112 maps/rooms/64room_000.map 512 512 472 263 72 360 451.978 +112 maps/rooms/64room_000.map 512 512 122 87 70 478 451.475 +112 maps/rooms/64room_000.map 512 512 209 321 492 209 451.233 +112 maps/rooms/64room_000.map 512 512 424 300 507 19 449.831 +112 maps/rooms/64room_000.map 512 512 103 345 146 37 450.806 +112 maps/rooms/64room_000.map 512 512 452 224 152 432 449.747 +112 maps/rooms/64room_000.map 512 512 249 110 439 394 451.647 +112 maps/rooms/64room_000.map 512 512 54 372 388 367 449.451 +112 maps/rooms/64room_000.map 512 512 72 405 415 353 449.333 +113 maps/rooms/64room_000.map 512 512 250 366 80 59 453.274 +113 maps/rooms/64room_000.map 512 512 397 13 46 94 452.576 +113 maps/rooms/64room_000.map 512 512 152 393 252 62 454.966 +113 maps/rooms/64room_000.map 512 512 457 134 405 464 454.291 +113 maps/rooms/64room_000.map 512 512 339 152 81 420 453.161 +113 maps/rooms/64room_000.map 512 512 463 409 175 460 453.073 +113 maps/rooms/64room_000.map 512 512 198 459 104 86 454.12 +113 maps/rooms/64room_000.map 512 512 137 150 43 498 454.215 +113 maps/rooms/64room_000.map 512 512 388 426 408 38 453.078 +113 maps/rooms/64room_000.map 512 512 258 32 331 371 453.522 +114 maps/rooms/64room_000.map 512 512 98 441 401 219 457.534 +114 maps/rooms/64room_000.map 512 512 113 451 168 127 456.203 +114 maps/rooms/64room_000.map 512 512 186 146 209 443 456.475 +114 maps/rooms/64room_000.map 512 512 190 13 440 293 458.676 +114 maps/rooms/64room_000.map 512 512 201 151 460 33 456.671 +114 maps/rooms/64room_000.map 512 512 125 427 248 84 458.534 +114 maps/rooms/64room_000.map 512 512 219 442 113 78 456.534 +114 maps/rooms/64room_000.map 512 512 480 424 404 124 458.936 +114 maps/rooms/64room_000.map 512 512 137 455 155 89 458.818 +114 maps/rooms/64room_000.map 512 512 330 424 203 56 457.274 +115 maps/rooms/64room_000.map 512 512 440 299 158 29 461.203 +115 maps/rooms/64room_000.map 512 512 61 490 367 304 460.635 +115 maps/rooms/64room_000.map 512 512 364 376 179 5 461.103 +115 maps/rooms/64room_000.map 512 512 428 206 459 479 462.517 +115 maps/rooms/64room_000.map 512 512 184 65 12 422 461.156 +115 maps/rooms/64room_000.map 512 512 300 73 339 408 462.517 +115 maps/rooms/64room_000.map 512 512 481 279 94 301 461.375 +115 maps/rooms/64room_000.map 512 512 218 447 404 153 460.96 +115 maps/rooms/64room_000.map 512 512 189 45 222 418 462.108 +115 maps/rooms/64room_000.map 512 512 342 398 187 19 462.475 +116 maps/rooms/64room_000.map 512 512 153 378 362 39 465.546 +116 maps/rooms/64room_000.map 512 512 228 105 383 488 467.789 +116 maps/rooms/64room_000.map 512 512 446 382 347 2 466.948 +116 maps/rooms/64room_000.map 512 512 220 432 430 161 467.718 +116 maps/rooms/64room_000.map 512 512 381 73 36 18 467.831 +116 maps/rooms/64room_000.map 512 512 405 326 318 127 467.328 +116 maps/rooms/64room_000.map 512 512 410 356 9 360 467.09 +116 maps/rooms/64room_000.map 512 512 460 508 315 177 465.161 +116 maps/rooms/64room_000.map 512 512 201 487 423 214 466.563 +116 maps/rooms/64room_000.map 512 512 378 143 38 265 464.784 +117 maps/rooms/64room_000.map 512 512 108 197 445 411 469.132 +117 maps/rooms/64room_000.map 512 512 490 221 106 180 471.836 +117 maps/rooms/64room_000.map 512 512 340 173 69 451 470.647 +117 maps/rooms/64room_000.map 512 512 493 172 172 11 470.458 +117 maps/rooms/64room_000.map 512 512 67 351 258 14 469.203 +117 maps/rooms/64room_000.map 512 512 235 396 451 196 469.345 +117 maps/rooms/64room_000.map 512 512 321 349 42 425 468.345 +117 maps/rooms/64room_000.map 512 512 499 43 164 245 468.813 +117 maps/rooms/64room_000.map 512 512 443 333 220 39 469.416 +117 maps/rooms/64room_000.map 512 512 338 438 198 51 469.718 +118 maps/rooms/64room_000.map 512 512 203 462 163 183 472.345 +118 maps/rooms/64room_000.map 512 512 232 274 480 60 473.872 +118 maps/rooms/64room_000.map 512 512 466 218 113 141 472.926 +118 maps/rooms/64room_000.map 512 512 73 407 341 485 473.914 +118 maps/rooms/64room_000.map 512 512 14 261 427 269 474.706 +118 maps/rooms/64room_000.map 512 512 377 43 28 3 472.73 +118 maps/rooms/64room_000.map 512 512 25 385 352 359 473.191 +118 maps/rooms/64room_000.map 512 512 120 207 489 115 472.328 +118 maps/rooms/64room_000.map 512 512 235 490 410 230 474.789 +118 maps/rooms/64room_000.map 512 512 330 173 54 447 475.831 +119 maps/rooms/64room_000.map 512 512 463 311 30 346 478.451 +119 maps/rooms/64room_000.map 512 512 364 232 95 35 479.931 +119 maps/rooms/64room_000.map 512 512 215 460 286 87 476.877 +119 maps/rooms/64room_000.map 512 512 207 17 435 323 477.688 +119 maps/rooms/64room_000.map 512 512 54 246 477 251 476.291 +119 maps/rooms/64room_000.map 512 512 67 367 470 228 477.304 +119 maps/rooms/64room_000.map 512 512 300 427 381 30 478.492 +119 maps/rooms/64room_000.map 512 512 394 451 101 442 476.517 +119 maps/rooms/64room_000.map 512 512 88 371 477 372 478.576 +119 maps/rooms/64room_000.map 512 512 269 412 94 67 476.416 +120 maps/rooms/64room_000.map 512 512 381 333 102 76 480.073 +120 maps/rooms/64room_000.map 512 512 60 489 68 88 483.801 +120 maps/rooms/64room_000.map 512 512 39 103 407 145 483.688 +120 maps/rooms/64room_000.map 512 512 255 379 259 24 483.617 +120 maps/rooms/64room_000.map 512 512 282 49 341 433 480.338 +120 maps/rooms/64room_000.map 512 512 469 16 160 123 481.044 +120 maps/rooms/64room_000.map 512 512 18 385 396 339 481.404 +120 maps/rooms/64room_000.map 512 512 308 28 61 263 481.487 +120 maps/rooms/64room_000.map 512 512 208 112 427 465 481.789 +120 maps/rooms/64room_000.map 512 512 312 211 38 511 482.032 +121 maps/rooms/64room_000.map 512 512 363 234 110 42 486.688 +121 maps/rooms/64room_000.map 512 512 25 511 330 389 487.357 +121 maps/rooms/64room_000.map 512 512 201 471 321 117 486.777 +121 maps/rooms/64room_000.map 512 512 184 96 352 463 487.073 +121 maps/rooms/64room_000.map 512 512 485 486 408 152 484.203 +121 maps/rooms/64room_000.map 512 512 114 449 440 477 487.061 +121 maps/rooms/64room_000.map 512 512 114 93 425 319 487.416 +121 maps/rooms/64room_000.map 512 512 419 87 411 491 486.09 +121 maps/rooms/64room_000.map 512 512 200 390 405 134 486.99 +121 maps/rooms/64room_000.map 512 512 458 297 86 432 484.179 +122 maps/rooms/64room_000.map 512 512 115 40 383 155 491.541 +122 maps/rooms/64room_000.map 512 512 504 149 239 363 489.659 +122 maps/rooms/64room_000.map 512 512 456 113 358 460 489.191 +122 maps/rooms/64room_000.map 512 512 383 166 459 505 490.546 +122 maps/rooms/64room_000.map 512 512 440 406 63 371 490.759 +122 maps/rooms/64room_000.map 512 512 262 159 490 495 489.161 +122 maps/rooms/64room_000.map 512 512 435 464 122 415 488.416 +122 maps/rooms/64room_000.map 512 512 234 430 396 131 488.605 +122 maps/rooms/64room_000.map 512 512 474 33 132 60 491.659 +122 maps/rooms/64room_000.map 512 512 33 288 367 53 490.754 +123 maps/rooms/64room_000.map 512 512 313 402 280 82 492.404 +123 maps/rooms/64room_000.map 512 512 127 27 232 346 494.701 +123 maps/rooms/64room_000.map 512 512 267 394 511 169 493.902 +123 maps/rooms/64room_000.map 512 512 75 469 399 218 492.647 +123 maps/rooms/64room_000.map 512 512 469 273 15 301 492.794 +123 maps/rooms/64room_000.map 512 512 331 273 37 29 495.931 +123 maps/rooms/64room_000.map 512 512 42 310 455 249 492.049 +123 maps/rooms/64room_000.map 512 512 353 439 305 74 495.617 +123 maps/rooms/64room_000.map 512 512 388 71 13 329 495.926 +123 maps/rooms/64room_000.map 512 512 484 293 176 30 493.96 +124 maps/rooms/64room_000.map 512 512 35 328 452 441 497.831 +124 maps/rooms/64room_000.map 512 512 343 84 251 429 496.99 +124 maps/rooms/64room_000.map 512 512 341 335 17 494 497.416 +124 maps/rooms/64room_000.map 512 512 489 78 103 226 499.612 +124 maps/rooms/64room_000.map 512 512 66 331 412 55 497.813 +124 maps/rooms/64room_000.map 512 512 92 388 408 116 498.96 +124 maps/rooms/64room_000.map 512 512 449 397 84 192 498.434 +124 maps/rooms/64room_000.map 512 512 510 139 97 294 496.073 +124 maps/rooms/64room_000.map 512 512 175 184 294 420 496.269 +124 maps/rooms/64room_000.map 512 512 474 145 444 484 496.789 +125 maps/rooms/64room_000.map 512 512 458 103 235 345 501.174 +125 maps/rooms/64room_000.map 512 512 341 70 45 146 503.304 +125 maps/rooms/64room_000.map 512 512 33 229 339 450 502.144 +125 maps/rooms/64room_000.map 512 512 321 69 496 436 500.149 +125 maps/rooms/64room_000.map 512 512 165 403 25 57 503.63 +125 maps/rooms/64room_000.map 512 512 78 501 406 278 503.877 +125 maps/rooms/64room_000.map 512 512 14 89 356 318 503.357 +125 maps/rooms/64room_000.map 512 512 82 400 487 328 502.22 +125 maps/rooms/64room_000.map 512 512 454 207 491 490 500.576 +125 maps/rooms/64room_000.map 512 512 117 126 348 447 502.6 +126 maps/rooms/64room_000.map 512 512 247 321 355 38 507.416 +126 maps/rooms/64room_000.map 512 512 425 89 142 413 507.073 +126 maps/rooms/64room_000.map 512 512 134 488 185 52 504.605 +126 maps/rooms/64room_000.map 512 512 59 298 452 406 504.002 +126 maps/rooms/64room_000.map 512 512 355 28 175 415 506.647 +126 maps/rooms/64room_000.map 512 512 14 50 403 106 505.843 +126 maps/rooms/64room_000.map 512 512 433 250 247 468 506.032 +126 maps/rooms/64room_000.map 512 512 182 119 409 497 506.044 +126 maps/rooms/64room_000.map 512 512 172 468 354 124 504.659 +126 maps/rooms/64room_000.map 512 512 204 3 365 423 507.274 +127 maps/rooms/64room_000.map 512 512 453 157 226 416 511.044 +127 maps/rooms/64room_000.map 512 512 106 404 143 39 510.617 +127 maps/rooms/64room_000.map 512 512 195 396 476 165 509.546 +127 maps/rooms/64room_000.map 512 512 97 87 13 505 509.428 +127 maps/rooms/64room_000.map 512 512 96 462 403 198 509.659 +127 maps/rooms/64room_000.map 512 512 28 95 385 194 510.132 +127 maps/rooms/64room_000.map 512 512 482 363 121 407 509.233 +127 maps/rooms/64room_000.map 512 512 315 125 463 271 509.328 +127 maps/rooms/64room_000.map 512 512 356 94 81 419 509.203 +127 maps/rooms/64room_000.map 512 512 76 507 421 340 510.801 +128 maps/rooms/64room_000.map 512 512 409 328 32 471 514.617 +128 maps/rooms/64room_000.map 512 512 188 508 398 241 513.399 +128 maps/rooms/64room_000.map 512 512 431 46 104 11 515.973 +128 maps/rooms/64room_000.map 512 512 132 433 259 19 513.659 +128 maps/rooms/64room_000.map 512 512 56 494 397 269 513.362 +128 maps/rooms/64room_000.map 512 512 307 425 441 32 513.919 +128 maps/rooms/64room_000.map 512 512 156 172 221 511 514.902 +128 maps/rooms/64room_000.map 512 512 174 428 49 14 515.416 +128 maps/rooms/64room_000.map 512 512 423 24 455 390 515.421 +128 maps/rooms/64room_000.map 512 512 174 183 380 405 515.63 +129 maps/rooms/64room_000.map 512 512 413 379 85 124 517.115 +129 maps/rooms/64room_000.map 512 512 502 80 428 441 518.428 +129 maps/rooms/64room_000.map 512 512 475 109 65 299 519.269 +129 maps/rooms/64room_000.map 512 512 413 478 185 84 518.902 +129 maps/rooms/64room_000.map 512 512 439 428 151 73 517.642 +129 maps/rooms/64room_000.map 512 512 35 411 400 471 518.227 +129 maps/rooms/64room_000.map 512 512 426 466 200 77 519.517 +129 maps/rooms/64room_000.map 512 512 297 11 6 352 519.269 +129 maps/rooms/64room_000.map 512 512 56 385 328 181 516.174 +129 maps/rooms/64room_000.map 512 512 459 202 53 372 518.333 +130 maps/rooms/64room_000.map 512 512 425 183 53 444 521.701 +130 maps/rooms/64room_000.map 512 512 71 99 452 211 520.612 +130 maps/rooms/64room_000.map 512 512 414 82 6 165 520.304 +130 maps/rooms/64room_000.map 512 512 50 204 435 127 522.098 +130 maps/rooms/64room_000.map 512 512 51 277 462 254 521.605 +130 maps/rooms/64room_000.map 512 512 145 479 511 496 522.186 +130 maps/rooms/64room_000.map 512 512 333 471 487 118 523.6 +130 maps/rooms/64room_000.map 512 512 156 166 509 237 520.926 +130 maps/rooms/64room_000.map 512 512 494 342 29 354 521.635 +130 maps/rooms/64room_000.map 512 512 479 366 104 426 521.777 +131 maps/rooms/64room_000.map 512 512 500 341 275 112 525.63 +131 maps/rooms/64room_000.map 512 512 96 410 227 4 525.558 +131 maps/rooms/64room_000.map 512 512 484 79 465 399 526.362 +131 maps/rooms/64room_000.map 512 512 403 111 14 35 525.843 +131 maps/rooms/64room_000.map 512 512 343 2 101 357 527.032 +131 maps/rooms/64room_000.map 512 512 436 416 413 2 526.806 +131 maps/rooms/64room_000.map 512 512 487 390 402 34 527.551 +131 maps/rooms/64room_000.map 512 512 460 407 144 107 526.96 +131 maps/rooms/64room_000.map 512 512 339 338 80 29 526.156 +131 maps/rooms/64room_000.map 512 512 226 493 257 127 527.191 +132 maps/rooms/64room_000.map 512 512 356 342 81 29 529.328 +132 maps/rooms/64room_000.map 512 512 28 496 367 497 529.529 +132 maps/rooms/64room_000.map 512 512 471 200 159 450 531.487 +132 maps/rooms/64room_000.map 512 512 115 369 488 480 529.772 +132 maps/rooms/64room_000.map 512 512 389 13 107 345 529.647 +132 maps/rooms/64room_000.map 512 512 485 95 230 328 529.387 +132 maps/rooms/64room_000.map 512 512 465 205 11 304 529.676 +132 maps/rooms/64room_000.map 512 512 431 115 475 453 530.919 +132 maps/rooms/64room_000.map 512 512 356 299 7 46 530.257 +132 maps/rooms/64room_000.map 512 512 319 77 414 419 530.044 +133 maps/rooms/64room_000.map 512 512 474 507 330 102 532.848 +133 maps/rooms/64room_000.map 512 512 135 420 354 27 535.831 +133 maps/rooms/64room_000.map 512 512 164 446 39 36 533.759 +133 maps/rooms/64room_000.map 512 512 139 24 393 417 532.186 +133 maps/rooms/64room_000.map 512 512 21 104 9 454 534.316 +133 maps/rooms/64room_000.map 512 512 145 34 325 446 535.73 +133 maps/rooms/64room_000.map 512 512 492 446 126 218 534.801 +133 maps/rooms/64room_000.map 512 512 478 342 486 41 532.227 +133 maps/rooms/64room_000.map 512 512 355 372 29 102 534.801 +133 maps/rooms/64room_000.map 512 512 86 474 110 39 532.085 +134 maps/rooms/64room_000.map 512 512 114 151 492 7 539.872 +134 maps/rooms/64room_000.map 512 512 243 132 463 486 537.227 +134 maps/rooms/64room_000.map 512 512 476 52 489 321 539.973 +134 maps/rooms/64room_000.map 512 512 107 492 425 175 538.772 +134 maps/rooms/64room_000.map 512 512 70 382 330 8 538.843 +134 maps/rooms/64room_000.map 512 512 393 255 89 501 536.617 +134 maps/rooms/64room_000.map 512 512 496 221 90 417 537.647 +134 maps/rooms/64room_000.map 512 512 16 226 426 426 538.642 +134 maps/rooms/64room_000.map 512 512 15 388 422 450 539.156 +134 maps/rooms/64room_000.map 512 512 349 30 211 441 536.789 +135 maps/rooms/64room_000.map 512 512 7 39 435 18 542.085 +135 maps/rooms/64room_000.map 512 512 61 63 252 414 543.044 +135 maps/rooms/64room_000.map 512 512 470 362 206 2 543.73 +135 maps/rooms/64room_000.map 512 512 90 310 507 463 540.257 +135 maps/rooms/64room_000.map 512 512 41 69 441 152 542.754 +135 maps/rooms/64room_000.map 512 512 500 441 36 316 540.487 +135 maps/rooms/64room_000.map 512 512 219 59 116 489 543.233 +135 maps/rooms/64room_000.map 512 512 15 482 89 48 541.754 +135 maps/rooms/64room_000.map 512 512 494 329 250 57 543.789 +135 maps/rooms/64room_000.map 512 512 207 14 166 466 540.789 +136 maps/rooms/64room_000.map 512 512 390 208 31 34 546.245 +136 maps/rooms/64room_000.map 512 512 481 52 152 316 546.286 +136 maps/rooms/64room_000.map 512 512 433 118 80 413 547.831 +136 maps/rooms/64room_000.map 512 512 21 23 60 397 545.742 +136 maps/rooms/64room_000.map 512 512 4 91 438 129 545.688 +136 maps/rooms/64room_000.map 512 512 452 361 156 191 547.688 +136 maps/rooms/64room_000.map 512 512 204 47 98 459 546.458 +136 maps/rooms/64room_000.map 512 512 20 507 418 457 545.085 +136 maps/rooms/64room_000.map 512 512 398 212 125 45 544.558 +136 maps/rooms/64room_000.map 512 512 394 10 335 475 546.978 +137 maps/rooms/64room_000.map 512 512 229 53 346 457 550.387 +137 maps/rooms/64room_000.map 512 512 155 463 20 83 551.156 +137 maps/rooms/64room_000.map 512 512 50 447 333 99 550.387 +137 maps/rooms/64room_000.map 512 512 475 318 46 432 548.647 +137 maps/rooms/64room_000.map 512 512 388 497 277 100 548.5 +137 maps/rooms/64room_000.map 512 512 99 166 324 467 548.257 +137 maps/rooms/64room_000.map 512 512 71 134 511 259 550.546 +137 maps/rooms/64room_000.map 512 512 284 67 377 500 550.115 +137 maps/rooms/64room_000.map 512 512 468 57 163 323 548.63 +137 maps/rooms/64room_000.map 512 512 474 480 505 166 549.701 +138 maps/rooms/64room_000.map 512 512 485 30 410 431 554.985 +138 maps/rooms/64room_000.map 512 512 54 498 412 194 553.63 +138 maps/rooms/64room_000.map 512 512 447 10 225 378 554.5 +138 maps/rooms/64room_000.map 512 512 402 149 119 10 553.98 +138 maps/rooms/64room_000.map 512 512 493 462 450 94 553.718 +138 maps/rooms/64room_000.map 512 512 434 435 46 404 553.926 +138 maps/rooms/64room_000.map 512 512 488 317 163 510 555.127 +138 maps/rooms/64room_000.map 512 512 2 60 130 450 555.47 +138 maps/rooms/64room_000.map 512 512 478 2 490 313 555.198 +138 maps/rooms/64room_000.map 512 512 196 61 25 473 553.399 +139 maps/rooms/64room_000.map 512 512 277 26 472 387 559.764 +139 maps/rooms/64room_000.map 512 512 464 341 74 510 559.985 +139 maps/rooms/64room_000.map 512 512 333 1 270 397 556.002 +139 maps/rooms/64room_000.map 512 512 13 169 165 439 559.446 +139 maps/rooms/64room_000.map 512 512 216 416 29 13 558.458 +139 maps/rooms/64room_000.map 512 512 51 489 50 49 558.227 +139 maps/rooms/64room_000.map 512 512 180 351 470 52 559.115 +139 maps/rooms/64room_000.map 512 512 2 422 265 36 558.11 +139 maps/rooms/64room_000.map 512 512 266 32 172 469 558.286 +139 maps/rooms/64room_000.map 512 512 62 463 22 151 558.115 +140 maps/rooms/64room_000.map 512 512 511 87 52 252 562.399 +140 maps/rooms/64room_000.map 512 512 403 267 10 79 561.399 +140 maps/rooms/64room_000.map 512 512 499 209 71 82 561.382 +140 maps/rooms/64room_000.map 512 512 12 170 404 185 563.441 +140 maps/rooms/64room_000.map 512 512 68 82 495 215 561.11 +140 maps/rooms/64room_000.map 512 512 148 497 446 135 563.713 +140 maps/rooms/64room_000.map 512 512 41 383 433 112 562.495 +140 maps/rooms/64room_000.map 512 512 41 40 245 436 561.286 +140 maps/rooms/64room_000.map 512 512 506 447 106 418 562.085 +140 maps/rooms/64room_000.map 512 512 490 336 242 4 560.6 +141 maps/rooms/64room_000.map 512 512 450 301 38 122 564.487 +141 maps/rooms/64room_000.map 512 512 6 344 490 168 565.688 +141 maps/rooms/64room_000.map 512 512 480 13 186 289 565.813 +141 maps/rooms/64room_000.map 512 512 259 111 54 478 565.446 +141 maps/rooms/64room_000.map 512 512 392 86 147 491 567.328 +141 maps/rooms/64room_000.map 512 512 484 416 286 45 566.907 +141 maps/rooms/64room_000.map 512 512 487 85 98 370 565.044 +141 maps/rooms/64room_000.map 512 512 471 305 38 389 564.848 +141 maps/rooms/64room_000.map 512 512 502 3 482 338 564.186 +141 maps/rooms/64room_000.map 512 512 258 114 109 456 564.647 +142 maps/rooms/64room_000.map 512 512 101 503 298 55 571.759 +142 maps/rooms/64room_000.map 512 512 81 363 484 76 568.156 +142 maps/rooms/64room_000.map 512 512 83 481 343 97 570.274 +142 maps/rooms/64room_000.map 512 512 250 454 464 146 568.718 +142 maps/rooms/64room_000.map 512 512 3 483 337 130 569.5 +142 maps/rooms/64room_000.map 512 512 76 272 508 37 571.441 +142 maps/rooms/64room_000.map 512 512 5 451 403 178 569.943 +142 maps/rooms/64room_000.map 512 512 25 8 390 202 569.014 +142 maps/rooms/64room_000.map 512 512 430 244 101 30 570.813 +142 maps/rooms/64room_000.map 512 512 439 376 62 126 568.955 +143 maps/rooms/64room_000.map 512 512 469 362 123 88 574.357 +143 maps/rooms/64room_000.map 512 512 478 51 101 233 574.796 +143 maps/rooms/64room_000.map 512 512 456 425 189 12 575.772 +143 maps/rooms/64room_000.map 512 512 15 117 507 72 572.487 +143 maps/rooms/64room_000.map 512 512 50 478 416 155 573.014 +143 maps/rooms/64room_000.map 512 512 46 136 340 328 572.357 +143 maps/rooms/64room_000.map 512 512 416 3 424 484 574.848 +143 maps/rooms/64room_000.map 512 512 422 481 133 65 574.955 +143 maps/rooms/64room_000.map 512 512 53 102 459 330 573.286 +143 maps/rooms/64room_000.map 512 512 105 399 453 122 574.245 +144 maps/rooms/64room_000.map 512 512 120 187 439 494 577.914 +144 maps/rooms/64room_000.map 512 512 104 213 460 44 576.796 +144 maps/rooms/64room_000.map 512 512 107 212 464 468 578.127 +144 maps/rooms/64room_000.map 512 512 53 474 275 53 578.73 +144 maps/rooms/64room_000.map 512 512 463 444 295 118 578.382 +144 maps/rooms/64room_000.map 512 512 507 78 252 321 579.713 +144 maps/rooms/64room_000.map 512 512 46 49 337 373 579.784 +144 maps/rooms/64room_000.map 512 512 452 474 87 501 579.186 +144 maps/rooms/64room_000.map 512 512 346 365 127 35 578.955 +144 maps/rooms/64room_000.map 512 512 142 446 474 83 578.671 +145 maps/rooms/64room_000.map 512 512 467 198 58 38 581.139 +145 maps/rooms/64room_000.map 512 512 35 58 423 230 582.843 +145 maps/rooms/64room_000.map 512 512 418 212 32 5 581.257 +145 maps/rooms/64room_000.map 512 512 126 164 434 481 583.056 +145 maps/rooms/64room_000.map 512 512 218 489 101 19 583.014 +145 maps/rooms/64room_000.map 512 512 108 54 440 281 583.156 +145 maps/rooms/64room_000.map 512 512 478 68 98 11 583.784 +145 maps/rooms/64room_000.map 512 512 24 120 472 242 582.767 +145 maps/rooms/64room_000.map 512 512 187 19 386 505 583.073 +145 maps/rooms/64room_000.map 512 512 29 497 199 54 581.642 +146 maps/rooms/64room_000.map 512 512 1 422 459 241 585.659 +146 maps/rooms/64room_000.map 512 512 30 27 410 254 586.428 +146 maps/rooms/64room_000.map 512 512 86 19 441 238 584.115 +146 maps/rooms/64room_000.map 512 512 423 467 266 35 585.735 +146 maps/rooms/64room_000.map 512 512 487 33 350 473 586.47 +146 maps/rooms/64room_000.map 512 512 432 77 118 431 585.286 +146 maps/rooms/64room_000.map 512 512 22 28 23 477 587.855 +146 maps/rooms/64room_000.map 512 512 416 326 49 37 586.399 +146 maps/rooms/64room_000.map 512 512 21 502 461 442 586.34 +146 maps/rooms/64room_000.map 512 512 106 16 443 215 586.708 +147 maps/rooms/64room_000.map 512 512 137 13 248 504 590.902 +147 maps/rooms/64room_000.map 512 512 214 3 409 475 591.014 +147 maps/rooms/64room_000.map 512 512 106 471 462 205 590.115 +147 maps/rooms/64room_000.map 512 512 509 72 247 397 590.37 +147 maps/rooms/64room_000.map 512 512 83 465 268 25 591.659 +147 maps/rooms/64room_000.map 512 512 87 234 455 458 588.441 +147 maps/rooms/64room_000.map 512 512 30 70 326 437 589.482 +147 maps/rooms/64room_000.map 512 512 118 389 460 491 588.583 +147 maps/rooms/64room_000.map 512 512 32 21 61 507 590.914 +147 maps/rooms/64room_000.map 512 512 103 455 305 41 588.316 +148 maps/rooms/64room_000.map 512 512 477 483 21 328 593.257 +148 maps/rooms/64room_000.map 512 512 222 9 416 456 594.914 +148 maps/rooms/64room_000.map 512 512 409 474 106 110 595.257 +148 maps/rooms/64room_000.map 512 512 30 92 392 395 592.671 +148 maps/rooms/64room_000.map 512 512 361 419 17 116 592.973 +148 maps/rooms/64room_000.map 512 512 1 499 49 51 595.453 +148 maps/rooms/64room_000.map 512 512 271 2 478 414 595.818 +148 maps/rooms/64room_000.map 512 512 23 34 350 373 593.671 +148 maps/rooms/64room_000.map 512 512 118 458 462 499 595.985 +148 maps/rooms/64room_000.map 512 512 493 314 40 475 593.546 +149 maps/rooms/64room_000.map 512 512 398 502 310 124 599.997 +149 maps/rooms/64room_000.map 512 512 15 501 122 40 597.068 +149 maps/rooms/64room_000.map 512 512 330 71 27 446 596.222 +149 maps/rooms/64room_000.map 512 512 498 432 163 150 599.642 +149 maps/rooms/64room_000.map 512 512 434 504 284 27 597.375 +149 maps/rooms/64room_000.map 512 512 497 59 239 324 596.127 +149 maps/rooms/64room_000.map 512 512 445 504 70 151 596.198 +149 maps/rooms/64room_000.map 512 512 327 66 100 502 599.902 +149 maps/rooms/64room_000.map 512 512 92 35 469 158 598.08 +149 maps/rooms/64room_000.map 512 512 46 490 278 50 598.215 +150 maps/rooms/64room_000.map 512 512 36 458 506 431 600.186 +150 maps/rooms/64room_000.map 512 512 8 21 406 303 600.056 +150 maps/rooms/64room_000.map 512 512 309 106 496 410 602.813 +150 maps/rooms/64room_000.map 512 512 14 169 281 430 601.914 +150 maps/rooms/64room_000.map 512 512 439 227 30 12 603.428 +150 maps/rooms/64room_000.map 512 512 15 47 241 474 600.914 +150 maps/rooms/64room_000.map 512 512 445 168 9 462 600.541 +150 maps/rooms/64room_000.map 512 512 236 50 440 453 601.943 +150 maps/rooms/64room_000.map 512 512 356 46 190 460 602.701 +150 maps/rooms/64room_000.map 512 512 35 478 452 376 600.671 +151 maps/rooms/64room_000.map 512 512 47 118 478 357 604.742 +151 maps/rooms/64room_000.map 512 512 92 451 492 504 606.328 +151 maps/rooms/64room_000.map 512 512 53 442 433 90 604.884 +151 maps/rooms/64room_000.map 512 512 410 381 6 126 606.813 +151 maps/rooms/64room_000.map 512 512 1 122 175 505 607.056 +151 maps/rooms/64room_000.map 512 512 239 55 443 455 605.044 +151 maps/rooms/64room_000.map 512 512 2 122 492 181 607.441 +151 maps/rooms/64room_000.map 512 512 301 77 495 451 604.541 +151 maps/rooms/64room_000.map 512 512 357 13 245 464 607.073 +151 maps/rooms/64room_000.map 512 512 31 53 333 381 606.098 +152 maps/rooms/64room_000.map 512 512 507 177 17 106 608.269 +152 maps/rooms/64room_000.map 512 512 190 510 480 156 610.624 +152 maps/rooms/64room_000.map 512 512 480 251 66 487 609.044 +152 maps/rooms/64room_000.map 512 512 378 409 100 37 608.825 +152 maps/rooms/64room_000.map 512 512 454 226 39 510 608.872 +152 maps/rooms/64room_000.map 512 512 337 485 509 19 609.328 +152 maps/rooms/64room_000.map 512 512 106 58 450 264 611.186 +152 maps/rooms/64room_000.map 512 512 33 45 421 327 610.299 +152 maps/rooms/64room_000.map 512 512 5 91 165 509 608.299 +152 maps/rooms/64room_000.map 512 512 500 45 62 214 609.34 +153 maps/rooms/64room_000.map 512 512 59 14 390 376 612.47 +153 maps/rooms/64room_000.map 512 512 133 341 477 5 612.683 +153 maps/rooms/64room_000.map 512 512 183 395 459 49 614.943 +153 maps/rooms/64room_000.map 512 512 223 469 425 27 613.872 +153 maps/rooms/64room_000.map 512 512 11 181 107 492 612.428 +153 maps/rooms/64room_000.map 512 512 487 121 44 259 612.98 +153 maps/rooms/64room_000.map 512 512 207 387 510 81 615.642 +153 maps/rooms/64room_000.map 512 512 423 198 51 175 612.495 +153 maps/rooms/64room_000.map 512 512 399 364 96 7 613.754 +153 maps/rooms/64room_000.map 512 512 49 165 292 412 614.198 +154 maps/rooms/64room_000.map 512 512 463 413 120 92 617.63 +154 maps/rooms/64room_000.map 512 512 25 16 137 495 618.796 +154 maps/rooms/64room_000.map 512 512 440 271 22 52 616.654 +154 maps/rooms/64room_000.map 512 512 456 403 96 82 618.044 +154 maps/rooms/64room_000.map 512 512 84 41 386 426 617.34 +154 maps/rooms/64room_000.map 512 512 459 407 456 34 617.872 +154 maps/rooms/64room_000.map 512 512 433 273 27 16 617.34 +154 maps/rooms/64room_000.map 512 512 26 85 366 440 617.399 +154 maps/rooms/64room_000.map 512 512 42 166 196 485 617.558 +154 maps/rooms/64room_000.map 512 512 431 153 7 493 618.725 +155 maps/rooms/64room_000.map 512 512 426 462 255 3 622.683 +155 maps/rooms/64room_000.map 512 512 478 308 5 101 623.772 +155 maps/rooms/64room_000.map 512 512 300 44 41 503 623.428 +155 maps/rooms/64room_000.map 512 512 445 77 27 407 621.335 +155 maps/rooms/64room_000.map 512 512 399 113 31 486 620.328 +155 maps/rooms/64room_000.map 512 512 143 383 459 39 622.825 +155 maps/rooms/64room_000.map 512 512 474 69 151 469 620.997 +155 maps/rooms/64room_000.map 512 512 214 3 425 509 623.441 +155 maps/rooms/64room_000.map 512 512 15 136 482 178 620.654 +155 maps/rooms/64room_000.map 512 512 381 449 31 103 621.328 +156 maps/rooms/64room_000.map 512 512 194 476 63 151 624.174 +156 maps/rooms/64room_000.map 512 512 141 5 491 409 625.127 +156 maps/rooms/64room_000.map 512 512 45 52 428 373 626.181 +156 maps/rooms/64room_000.map 512 512 56 140 440 216 627.453 +156 maps/rooms/64room_000.map 512 512 397 492 461 22 626.198 +156 maps/rooms/64room_000.map 512 512 4 150 484 196 625.855 +156 maps/rooms/64room_000.map 512 512 471 37 492 406 626.014 +156 maps/rooms/64room_000.map 512 512 63 475 459 488 627.583 +156 maps/rooms/64room_000.map 512 512 446 36 129 475 624.441 +156 maps/rooms/64room_000.map 512 512 475 304 59 47 626.47 +157 maps/rooms/64room_000.map 512 512 417 49 36 393 629.808 +157 maps/rooms/64room_000.map 512 512 105 38 398 405 631.169 +157 maps/rooms/64room_000.map 512 512 495 39 247 392 628.754 +157 maps/rooms/64room_000.map 512 512 108 61 505 232 630.909 +157 maps/rooms/64room_000.map 512 512 486 119 74 428 628.754 +157 maps/rooms/64room_000.map 512 512 483 7 105 328 630.813 +157 maps/rooms/64room_000.map 512 512 458 69 78 438 630.671 +157 maps/rooms/64room_000.map 512 512 30 488 470 451 631.441 +157 maps/rooms/64room_000.map 512 512 210 324 457 26 628.997 +157 maps/rooms/64room_000.map 512 512 50 507 318 65 630.073 +158 maps/rooms/64room_000.map 512 512 511 72 449 450 633.571 +158 maps/rooms/64room_000.map 512 512 398 505 112 85 635.428 +158 maps/rooms/64room_000.map 512 512 13 400 465 102 632.406 +158 maps/rooms/64room_000.map 512 512 468 84 216 511 634.286 +158 maps/rooms/64room_000.map 512 512 10 440 376 26 633.98 +158 maps/rooms/64room_000.map 512 512 278 20 56 500 634.073 +158 maps/rooms/64room_000.map 512 512 43 250 470 34 634.696 +158 maps/rooms/64room_000.map 512 512 34 14 429 354 632.21 +158 maps/rooms/64room_000.map 512 512 440 478 187 179 634.198 +158 maps/rooms/64room_000.map 512 512 452 22 68 232 633.495 +159 maps/rooms/64room_000.map 512 512 137 469 441 14 638.37 +159 maps/rooms/64room_000.map 512 512 452 261 94 13 638.642 +159 maps/rooms/64room_000.map 512 512 413 10 12 402 638.678 +159 maps/rooms/64room_000.map 512 512 449 32 266 428 638.227 +159 maps/rooms/64room_000.map 512 512 398 395 11 139 639.156 +159 maps/rooms/64room_000.map 512 512 316 31 54 504 638.671 +159 maps/rooms/64room_000.map 512 512 370 376 63 130 638.671 +159 maps/rooms/64room_000.map 512 512 5 454 499 224 639.144 +159 maps/rooms/64room_000.map 512 512 473 464 147 161 636.37 +159 maps/rooms/64room_000.map 512 512 496 2 52 234 639.897 +160 maps/rooms/64room_000.map 512 512 422 30 246 495 643.399 +160 maps/rooms/64room_000.map 512 512 392 103 44 506 640.428 +160 maps/rooms/64room_000.map 512 512 453 13 479 406 640.955 +160 maps/rooms/64room_000.map 512 512 443 406 30 106 640.671 +160 maps/rooms/64room_000.map 512 512 29 440 497 133 642.612 +160 maps/rooms/64room_000.map 512 512 297 49 487 508 642.505 +160 maps/rooms/64room_000.map 512 512 33 114 392 471 642.742 +160 maps/rooms/64room_000.map 512 512 497 248 49 45 643.749 +160 maps/rooms/64room_000.map 512 512 1 425 403 20 642.98 +160 maps/rooms/64room_000.map 512 512 2 150 390 396 642.357 +161 maps/rooms/64room_000.map 512 512 29 77 452 380 646.642 +161 maps/rooms/64room_000.map 512 512 48 252 469 10 647.909 +161 maps/rooms/64room_000.map 512 512 49 26 476 51 647.512 +161 maps/rooms/64room_000.map 512 512 468 312 118 16 645.21 +161 maps/rooms/64room_000.map 512 512 395 439 103 38 647.867 +161 maps/rooms/64room_000.map 512 512 411 55 59 416 646.529 +161 maps/rooms/64room_000.map 512 512 497 70 52 160 647.299 +161 maps/rooms/64room_000.map 512 512 354 379 62 162 647.299 +161 maps/rooms/64room_000.map 512 512 28 34 467 271 644.299 +161 maps/rooms/64room_000.map 512 512 126 84 323 481 646.441 +162 maps/rooms/64room_000.map 512 512 494 265 100 28 651.24 +162 maps/rooms/64room_000.map 512 512 18 478 487 148 651.382 +162 maps/rooms/64room_000.map 512 512 124 495 444 43 649.855 +162 maps/rooms/64room_000.map 512 512 61 263 510 47 648.495 +162 maps/rooms/64room_000.map 512 512 11 511 310 61 649.156 +162 maps/rooms/64room_000.map 512 512 496 211 7 479 649.884 +162 maps/rooms/64room_000.map 512 512 56 140 431 258 648.955 +162 maps/rooms/64room_000.map 512 512 434 260 8 3 648.11 +162 maps/rooms/64room_000.map 512 512 369 449 6 111 651.014 +162 maps/rooms/64room_000.map 512 512 183 477 14 7 648.21 +163 maps/rooms/64room_000.map 512 512 476 217 49 132 655.311 +163 maps/rooms/64room_000.map 512 512 510 36 2 258 654.583 +163 maps/rooms/64room_000.map 512 512 454 55 499 432 653.328 +163 maps/rooms/64room_000.map 512 512 456 452 61 402 653.926 +163 maps/rooms/64room_000.map 512 512 54 498 451 477 654.825 +163 maps/rooms/64room_000.map 512 512 71 459 457 126 653.156 +163 maps/rooms/64room_000.map 512 512 90 106 490 450 653.068 +163 maps/rooms/64room_000.map 512 512 464 27 47 314 655.82 +163 maps/rooms/64room_000.map 512 512 125 363 459 11 654.683 +163 maps/rooms/64room_000.map 512 512 449 79 76 473 652.772 +164 maps/rooms/64room_000.map 512 512 360 49 20 485 656.541 +164 maps/rooms/64room_000.map 512 512 41 190 146 486 657.683 +164 maps/rooms/64room_000.map 512 512 35 454 499 507 658.955 +164 maps/rooms/64room_000.map 512 512 408 435 92 25 657.696 +164 maps/rooms/64room_000.map 512 512 473 190 19 190 658.24 +164 maps/rooms/64room_000.map 512 512 453 394 60 69 656.215 +164 maps/rooms/64room_000.map 512 512 457 482 104 151 657.169 +164 maps/rooms/64room_000.map 512 512 447 111 55 494 657.257 +164 maps/rooms/64room_000.map 512 512 453 22 495 414 656.541 +164 maps/rooms/64room_000.map 512 512 420 44 108 495 659.014 +165 maps/rooms/64room_000.map 512 512 472 274 5 31 663.512 +165 maps/rooms/64room_000.map 512 512 482 54 36 9 660.311 +165 maps/rooms/64room_000.map 512 512 304 82 511 500 663.583 +165 maps/rooms/64room_000.map 512 512 476 82 187 496 661.281 +165 maps/rooms/64room_000.map 512 512 58 91 414 453 660.884 +165 maps/rooms/64room_000.map 512 512 181 469 498 92 661.955 +165 maps/rooms/64room_000.map 512 512 2 211 470 455 662.039 +165 maps/rooms/64room_000.map 512 512 100 23 456 367 661.754 +165 maps/rooms/64room_000.map 512 512 489 81 123 495 662.541 +165 maps/rooms/64room_000.map 512 512 13 432 450 83 662.164 +166 maps/rooms/64room_000.map 512 512 486 478 1 423 667.311 +166 maps/rooms/64room_000.map 512 512 424 27 179 501 665.382 +166 maps/rooms/64room_000.map 512 512 508 495 275 22 666.416 +166 maps/rooms/64room_000.map 512 512 232 15 461 461 666.21 +166 maps/rooms/64room_000.map 512 512 269 35 480 496 667.203 +166 maps/rooms/64room_000.map 512 512 474 349 104 14 666.553 +166 maps/rooms/64room_000.map 512 512 459 502 171 51 665.825 +166 maps/rooms/64room_000.map 512 512 332 490 87 65 664.725 +166 maps/rooms/64room_000.map 512 512 428 27 49 400 665.82 +166 maps/rooms/64room_000.map 512 512 96 405 494 39 666.198 +167 maps/rooms/64room_000.map 512 512 372 412 7 182 668.571 +167 maps/rooms/64room_000.map 512 512 400 484 73 47 669.411 +167 maps/rooms/64room_000.map 512 512 187 497 491 102 671.725 +167 maps/rooms/64room_000.map 512 512 473 78 57 453 669.583 +167 maps/rooms/64room_000.map 512 512 8 497 269 9 669.784 +167 maps/rooms/64room_000.map 512 512 42 37 488 344 670.37 +167 maps/rooms/64room_000.map 512 512 246 402 470 15 669.423 +167 maps/rooms/64room_000.map 512 512 491 394 42 105 669.186 +167 maps/rooms/64room_000.map 512 512 111 427 506 51 670.813 +167 maps/rooms/64room_000.map 512 512 5 489 275 1 670.299 +168 maps/rooms/64room_000.map 512 512 465 454 148 4 674.796 +168 maps/rooms/64room_000.map 512 512 77 486 469 86 672.156 +168 maps/rooms/64room_000.map 512 512 366 468 54 32 675.897 +168 maps/rooms/64room_000.map 512 512 61 405 493 510 673.683 +168 maps/rooms/64room_000.map 512 512 362 1 53 474 675.127 +168 maps/rooms/64room_000.map 512 512 464 50 119 16 675.524 +168 maps/rooms/64room_000.map 512 512 49 96 353 505 672.754 +168 maps/rooms/64room_000.map 512 512 129 411 449 61 675.328 +168 maps/rooms/64room_000.map 512 512 274 29 510 504 674.345 +168 maps/rooms/64room_000.map 512 512 495 1 495 455 673.612 +169 maps/rooms/64room_000.map 512 512 486 91 54 456 676.026 +169 maps/rooms/64room_000.map 512 512 458 76 19 444 678.127 +169 maps/rooms/64room_000.map 512 512 26 48 492 260 678.867 +169 maps/rooms/64room_000.map 512 512 473 492 251 53 677.926 +169 maps/rooms/64room_000.map 512 512 502 71 148 502 677.583 +169 maps/rooms/64room_000.map 512 512 502 487 141 29 679.583 +169 maps/rooms/64room_000.map 512 512 503 231 22 161 677.808 +169 maps/rooms/64room_000.map 512 512 31 182 323 407 677.098 +169 maps/rooms/64room_000.map 512 512 59 59 467 19 676.281 +169 maps/rooms/64room_000.map 512 512 457 270 13 185 678.428 +170 maps/rooms/64room_000.map 512 512 496 109 22 438 683.968 +170 maps/rooms/64room_000.map 512 512 417 407 23 152 681.098 +170 maps/rooms/64room_000.map 512 512 123 68 508 425 683.47 +170 maps/rooms/64room_000.map 512 512 69 345 451 4 683.448 +170 maps/rooms/64room_000.map 512 512 101 420 504 31 682.985 +170 maps/rooms/64room_000.map 512 512 507 44 224 483 683.127 +170 maps/rooms/64room_000.map 512 512 62 179 418 362 680.252 +170 maps/rooms/64room_000.map 512 512 452 471 1 472 680.098 +170 maps/rooms/64room_000.map 512 512 361 455 47 27 681.068 +170 maps/rooms/64room_000.map 512 512 455 463 133 46 682.612 +171 maps/rooms/64room_000.map 512 512 447 41 32 464 686.867 +171 maps/rooms/64room_000.map 512 512 501 33 97 422 685.884 +171 maps/rooms/64room_000.map 512 512 84 450 445 9 686.784 +171 maps/rooms/64room_000.map 512 512 377 481 85 25 684.34 +171 maps/rooms/64room_000.map 512 512 18 189 491 163 686.009 +171 maps/rooms/64room_000.map 512 512 455 50 15 145 684.713 +171 maps/rooms/64room_000.map 512 512 511 372 25 67 687.624 +171 maps/rooms/64room_000.map 512 512 43 349 454 30 686.205 +171 maps/rooms/64room_000.map 512 512 465 501 155 36 684.553 +171 maps/rooms/64room_000.map 512 512 505 476 454 62 687.541 +172 maps/rooms/64room_000.map 512 512 157 511 440 5 691.968 +172 maps/rooms/64room_000.map 512 512 360 22 32 501 690.47 +172 maps/rooms/64room_000.map 512 512 488 63 156 476 691.382 +172 maps/rooms/64room_000.map 512 512 466 38 251 434 689.725 +172 maps/rooms/64room_000.map 512 512 462 477 171 188 689.696 +172 maps/rooms/64room_000.map 512 512 41 511 452 96 691.269 +172 maps/rooms/64room_000.map 512 512 204 387 509 10 690.884 +172 maps/rooms/64room_000.map 512 512 22 155 465 44 690.098 +172 maps/rooms/64room_000.map 512 512 237 402 463 6 689.151 +172 maps/rooms/64room_000.map 512 512 482 30 7 285 690.933 +173 maps/rooms/64room_000.map 512 512 39 262 487 21 694.134 +173 maps/rooms/64room_000.map 512 512 9 171 510 15 695.257 +173 maps/rooms/64room_000.map 512 512 102 52 353 489 692.867 +173 maps/rooms/64room_000.map 512 512 29 411 501 76 694.661 +173 maps/rooms/64room_000.map 512 512 106 455 491 77 692.955 +173 maps/rooms/64room_000.map 512 512 406 428 23 2 693.323 +173 maps/rooms/64room_000.map 512 512 255 23 494 507 692.203 +173 maps/rooms/64room_000.map 512 512 435 473 24 114 695.571 +173 maps/rooms/64room_000.map 512 512 15 440 496 107 692.968 +173 maps/rooms/64room_000.map 512 512 163 29 455 510 692.595 +174 maps/rooms/64room_000.map 512 512 3 132 373 487 697.299 +174 maps/rooms/64room_000.map 512 512 63 53 397 451 696.482 +174 maps/rooms/64room_000.map 512 512 478 60 241 458 698.085 +174 maps/rooms/64room_000.map 512 512 488 378 81 3 698.139 +174 maps/rooms/64room_000.map 512 512 456 28 54 365 696.477 +174 maps/rooms/64room_000.map 512 512 470 321 28 174 698.855 +174 maps/rooms/64room_000.map 512 512 491 375 13 144 697.482 +174 maps/rooms/64room_000.map 512 512 170 453 482 62 699.926 +174 maps/rooms/64room_000.map 512 512 49 491 466 73 696.169 +174 maps/rooms/64room_000.map 512 512 2 34 414 425 696.11 +175 maps/rooms/64room_000.map 512 512 449 459 135 3 702.767 +175 maps/rooms/64room_000.map 512 512 425 491 14 116 703.855 +175 maps/rooms/64room_000.map 512 512 426 491 30 80 701.281 +175 maps/rooms/64room_000.map 512 512 204 493 481 43 702.47 +175 maps/rooms/64room_000.map 512 512 23 47 449 35 703.009 +175 maps/rooms/64room_000.map 512 512 48 273 454 24 700.619 +175 maps/rooms/64room_000.map 512 512 372 465 1 42 702.281 +175 maps/rooms/64room_000.map 512 512 73 43 436 470 701.269 +175 maps/rooms/64room_000.map 512 512 462 8 28 63 701.909 +175 maps/rooms/64room_000.map 512 512 474 15 2 315 701.82 +176 maps/rooms/64room_000.map 512 512 41 484 487 87 705.34 +176 maps/rooms/64room_000.map 512 512 178 490 504 54 705.737 +176 maps/rooms/64room_000.map 512 512 106 52 324 458 704.825 +176 maps/rooms/64room_000.map 512 512 465 26 22 165 707.553 +176 maps/rooms/64room_000.map 512 512 76 27 328 467 704.24 +176 maps/rooms/64room_000.map 512 512 122 47 450 407 704.541 +176 maps/rooms/64room_000.map 512 512 468 354 36 172 704.482 +176 maps/rooms/64room_000.map 512 512 19 332 451 13 707.933 +176 maps/rooms/64room_000.map 512 512 97 506 446 13 706.926 +176 maps/rooms/64room_000.map 512 512 17 490 473 90 707.796 +177 maps/rooms/64room_000.map 512 512 499 409 17 99 710.884 +177 maps/rooms/64room_000.map 512 512 400 52 6 508 708.825 +177 maps/rooms/64room_000.map 512 512 504 365 32 21 710.867 +177 maps/rooms/64room_000.map 512 512 20 500 356 5 711.24 +177 maps/rooms/64room_000.map 512 512 55 2 461 394 709.855 +177 maps/rooms/64room_000.map 512 512 120 23 402 471 711.252 +177 maps/rooms/64room_000.map 512 512 111 31 483 386 710.169 +177 maps/rooms/64room_000.map 512 512 18 49 442 433 708.566 +177 maps/rooms/64room_000.map 512 512 355 510 6 111 711.955 +177 maps/rooms/64room_000.map 512 512 462 400 32 36 709.37 +178 maps/rooms/64room_000.map 512 512 445 425 127 12 715.122 +178 maps/rooms/64room_000.map 512 512 103 422 471 15 713.825 +178 maps/rooms/64room_000.map 512 512 365 497 2 73 714.553 +178 maps/rooms/64room_000.map 512 512 505 427 27 104 712.269 +178 maps/rooms/64room_000.map 512 512 52 501 486 118 712.453 +178 maps/rooms/64room_000.map 512 512 213 501 481 48 712.127 +178 maps/rooms/64room_000.map 512 512 461 376 14 14 712.068 +178 maps/rooms/64room_000.map 512 512 476 1 490 489 715.897 +178 maps/rooms/64room_000.map 512 512 327 449 112 26 714.867 +178 maps/rooms/64room_000.map 512 512 485 107 66 509 713.299 +179 maps/rooms/64room_000.map 512 512 75 17 474 430 717.897 +179 maps/rooms/64room_000.map 512 512 486 476 52 122 718.382 +179 maps/rooms/64room_000.map 512 512 6 61 412 483 717.009 +179 maps/rooms/64room_000.map 512 512 401 451 107 9 718.08 +179 maps/rooms/64room_000.map 512 512 89 427 460 50 716.441 +179 maps/rooms/64room_000.map 512 512 503 335 38 153 719.299 +179 maps/rooms/64room_000.map 512 512 510 63 55 409 718.311 +179 maps/rooms/64room_000.map 512 512 490 5 140 464 716.453 +179 maps/rooms/64room_000.map 512 512 34 150 377 473 719.512 +179 maps/rooms/64room_000.map 512 512 239 464 467 43 716.612 +180 maps/rooms/64room_000.map 512 512 91 439 471 36 722.411 +180 maps/rooms/64room_000.map 512 512 10 127 496 427 722.34 +180 maps/rooms/64room_000.map 512 512 27 9 352 466 722.08 +180 maps/rooms/64room_000.map 512 512 93 65 492 480 720.24 +180 maps/rooms/64room_000.map 512 512 505 1 55 130 720.428 +180 maps/rooms/64room_000.map 512 512 505 54 89 467 722.311 +180 maps/rooms/64room_000.map 512 512 60 462 506 62 721.654 +180 maps/rooms/64room_000.map 512 512 402 452 12 150 720.583 +180 maps/rooms/64room_000.map 512 512 511 47 89 461 721.411 +180 maps/rooms/64room_000.map 512 512 18 367 462 7 723.703 +181 maps/rooms/64room_000.map 512 512 462 486 82 82 726.222 +181 maps/rooms/64room_000.map 512 512 492 390 42 42 725.37 +181 maps/rooms/64room_000.map 512 512 22 474 508 79 724.252 +181 maps/rooms/64room_000.map 512 512 451 21 44 383 726.519 +181 maps/rooms/64room_000.map 512 512 446 504 45 75 725.453 +181 maps/rooms/64room_000.map 512 512 488 12 86 433 727.825 +181 maps/rooms/64room_000.map 512 512 488 8 4 3 726.595 +181 maps/rooms/64room_000.map 512 512 495 51 111 505 725.553 +181 maps/rooms/64room_000.map 512 512 5 496 422 35 726.281 +181 maps/rooms/64room_000.map 512 512 8 18 453 23 726.423 +182 maps/rooms/64room_000.map 512 512 107 61 494 442 730.867 +182 maps/rooms/64room_000.map 512 512 485 379 51 136 731.926 +182 maps/rooms/64room_000.map 512 512 61 142 466 23 728.482 +182 maps/rooms/64room_000.map 512 512 446 502 18 124 728.725 +182 maps/rooms/64room_000.map 512 512 454 24 94 426 730.139 +182 maps/rooms/64room_000.map 512 512 488 447 16 72 730.737 +182 maps/rooms/64room_000.map 512 512 387 455 16 10 729.11 +182 maps/rooms/64room_000.map 512 512 113 75 455 492 730.11 +182 maps/rooms/64room_000.map 512 512 422 489 1 65 731.666 +182 maps/rooms/64room_000.map 512 512 203 504 470 29 729.855 +183 maps/rooms/64room_000.map 512 512 5 496 483 76 734.566 +183 maps/rooms/64room_000.map 512 512 498 66 37 493 733.352 +183 maps/rooms/64room_000.map 512 512 425 484 84 9 734.624 +183 maps/rooms/64room_000.map 512 512 470 503 72 96 735.323 +183 maps/rooms/64room_000.map 512 512 63 172 481 344 733.897 +183 maps/rooms/64room_000.map 512 512 339 489 2 48 733.536 +183 maps/rooms/64room_000.map 512 512 62 161 372 449 734.24 +183 maps/rooms/64room_000.map 512 512 431 470 122 41 734.382 +183 maps/rooms/64room_000.map 512 512 505 18 75 447 733.34 +183 maps/rooms/64room_000.map 512 512 74 431 460 30 734.938 +184 maps/rooms/64room_000.map 512 512 426 502 75 10 738.352 +184 maps/rooms/64room_000.map 512 512 56 166 444 388 738.441 +184 maps/rooms/64room_000.map 512 512 487 350 42 186 736.553 +184 maps/rooms/64room_000.map 512 512 28 178 441 414 736.068 +184 maps/rooms/64room_000.map 512 512 466 61 59 444 736.482 +184 maps/rooms/64room_000.map 512 512 478 33 18 395 739.016 +184 maps/rooms/64room_000.map 512 512 73 4 488 424 739.825 +184 maps/rooms/64room_000.map 512 512 444 496 15 73 739.252 +184 maps/rooms/64room_000.map 512 512 5 159 410 489 739.24 +184 maps/rooms/64room_000.map 512 512 496 420 12 62 739.938 +185 maps/rooms/64room_000.map 512 512 141 503 483 21 742.767 +185 maps/rooms/64room_000.map 512 512 134 484 470 5 742.252 +185 maps/rooms/64room_000.map 512 512 490 508 111 66 740.612 +185 maps/rooms/64room_000.map 512 512 70 69 459 479 740.779 +185 maps/rooms/64room_000.map 512 512 21 26 368 498 740.553 +185 maps/rooms/64room_000.map 512 512 446 497 58 37 740.181 +185 maps/rooms/64room_000.map 512 512 415 481 18 32 743.796 +185 maps/rooms/64room_000.map 512 512 73 453 507 14 743.34 +185 maps/rooms/64room_000.map 512 512 360 485 19 5 741.566 +185 maps/rooms/64room_000.map 512 512 3 17 398 457 743.524 +186 maps/rooms/64room_000.map 512 512 30 173 352 473 745.938 +186 maps/rooms/64room_000.map 512 512 431 455 21 52 745.423 +186 maps/rooms/64room_000.map 512 512 32 38 495 410 744.997 +186 maps/rooms/64room_000.map 512 512 328 502 89 7 745.293 +186 maps/rooms/64room_000.map 512 512 81 485 509 45 744.34 +186 maps/rooms/64room_000.map 512 512 375 490 48 134 744.713 +186 maps/rooms/64room_000.map 512 512 45 172 356 465 744.423 +186 maps/rooms/64room_000.map 512 512 31 41 430 483 747.039 +186 maps/rooms/64room_000.map 512 512 13 125 509 451 745.553 +186 maps/rooms/64room_000.map 512 512 28 1 415 478 745.394 +187 maps/rooms/64room_000.map 512 512 31 502 511 75 748.252 +187 maps/rooms/64room_000.map 512 512 495 54 11 440 751.318 +187 maps/rooms/64room_000.map 512 512 468 400 45 156 749.34 +187 maps/rooms/64room_000.map 512 512 27 46 334 501 751.637 +187 maps/rooms/64room_000.map 512 512 39 157 405 449 748.867 +187 maps/rooms/64room_000.map 512 512 40 148 378 500 751.269 +187 maps/rooms/64room_000.map 512 512 29 150 357 500 749.796 +187 maps/rooms/64room_000.map 512 512 20 16 336 484 749.637 +187 maps/rooms/64room_000.map 512 512 56 433 471 27 748.394 +187 maps/rooms/64room_000.map 512 512 351 478 10 182 750.311 +188 maps/rooms/64room_000.map 512 512 56 190 501 332 752.897 +188 maps/rooms/64room_000.map 512 512 501 19 15 412 753.389 +188 maps/rooms/64room_000.map 512 512 61 22 494 455 752.666 +188 maps/rooms/64room_000.map 512 512 28 99 508 482 753.767 +188 maps/rooms/64room_000.map 512 512 462 473 55 76 755.009 +188 maps/rooms/64room_000.map 512 512 37 27 330 511 752.879 +188 maps/rooms/64room_000.map 512 512 492 454 50 24 754.808 +188 maps/rooms/64room_000.map 512 512 441 505 126 60 755.009 +188 maps/rooms/64room_000.map 512 512 71 2 505 418 755.997 +188 maps/rooms/64room_000.map 512 512 108 38 498 458 755.536 +189 maps/rooms/64room_000.map 512 512 481 389 4 11 759.825 +189 maps/rooms/64room_000.map 512 512 493 10 120 506 756.453 +189 maps/rooms/64room_000.map 512 512 188 482 490 13 759.222 +189 maps/rooms/64room_000.map 512 512 16 11 465 444 757.536 +189 maps/rooms/64room_000.map 512 512 468 502 81 66 756.151 +189 maps/rooms/64room_000.map 512 512 442 498 40 27 757.909 +189 maps/rooms/64room_000.map 512 512 497 34 95 509 757.039 +189 maps/rooms/64room_000.map 512 512 47 423 478 26 757.293 +189 maps/rooms/64room_000.map 512 512 342 499 24 3 758.85 +189 maps/rooms/64room_000.map 512 512 456 478 32 100 759.151 +190 maps/rooms/64room_000.map 512 512 1 10 363 492 763.252 +190 maps/rooms/64room_000.map 512 512 37 164 401 497 761.767 +190 maps/rooms/64room_000.map 512 512 100 500 482 27 761.524 +190 maps/rooms/64room_000.map 512 512 9 167 366 510 760.683 +190 maps/rooms/64room_000.map 512 512 469 39 1 422 761.389 +190 maps/rooms/64room_000.map 512 512 29 96 503 491 760.938 +190 maps/rooms/64room_000.map 512 512 426 492 6 166 763.897 +190 maps/rooms/64room_000.map 512 512 501 33 74 489 762.411 +190 maps/rooms/64room_000.map 512 512 469 506 47 101 761.666 +190 maps/rooms/64room_000.map 512 512 35 426 493 26 761.838 +191 maps/rooms/64room_000.map 512 512 501 475 102 39 767.365 +191 maps/rooms/64room_000.map 512 512 492 33 57 386 766.732 +191 maps/rooms/64room_000.map 512 512 450 14 8 393 764.644 +191 maps/rooms/64room_000.map 512 512 9 166 482 437 766.725 +191 maps/rooms/64room_000.map 512 512 499 387 19 169 767.227 +191 maps/rooms/64room_000.map 512 512 459 404 23 191 764.37 +191 maps/rooms/64room_000.map 512 512 13 44 445 485 767.666 +191 maps/rooms/64room_000.map 512 512 177 490 452 27 766.749 +191 maps/rooms/64room_000.map 512 512 507 399 126 8 765.252 +191 maps/rooms/64room_000.map 512 512 36 2 505 408 767.524 +192 maps/rooms/64room_000.map 512 512 19 436 490 30 770.938 +192 maps/rooms/64room_000.map 512 512 324 492 1 174 770.796 +192 maps/rooms/64room_000.map 512 512 337 506 9 28 768.465 +192 maps/rooms/64room_000.map 512 512 413 472 18 187 768.583 +192 maps/rooms/64room_000.map 512 512 389 493 15 191 770.098 +192 maps/rooms/64room_000.map 512 512 124 489 455 28 769.252 +192 maps/rooms/64room_000.map 512 512 456 416 59 145 768.642 +192 maps/rooms/64room_000.map 512 512 113 47 510 468 771.779 +192 maps/rooms/64room_000.map 512 512 489 421 1 27 769.252 +192 maps/rooms/64room_000.map 512 512 482 495 35 79 769.909 +193 maps/rooms/64room_000.map 512 512 442 495 27 143 773.867 +193 maps/rooms/64room_000.map 512 512 497 440 31 13 772.051 +193 maps/rooms/64room_000.map 512 512 20 469 479 61 773.423 +193 maps/rooms/64room_000.map 512 512 86 48 460 489 773.164 +193 maps/rooms/64room_000.map 512 512 17 155 497 436 773.624 +193 maps/rooms/64room_000.map 512 512 476 23 95 474 774.808 +193 maps/rooms/64room_000.map 512 512 23 431 487 28 772.252 +193 maps/rooms/64room_000.map 512 512 12 484 495 58 772.879 +193 maps/rooms/64room_000.map 512 512 53 466 465 42 775.696 +193 maps/rooms/64room_000.map 512 512 47 469 463 63 772.725 +194 maps/rooms/64room_000.map 512 512 502 461 127 40 778.365 +194 maps/rooms/64room_000.map 512 512 12 90 506 488 778.666 +194 maps/rooms/64room_000.map 512 512 452 32 171 506 776.436 +194 maps/rooms/64room_000.map 512 512 11 431 460 52 778.146 +194 maps/rooms/64room_000.map 512 512 416 478 50 174 776.666 +194 maps/rooms/64room_000.map 512 512 50 180 351 491 777.879 +194 maps/rooms/64room_000.map 512 512 59 470 490 9 779.352 +194 maps/rooms/64room_000.map 512 512 106 455 463 40 777.453 +194 maps/rooms/64room_000.map 512 512 101 478 460 53 776.767 +194 maps/rooms/64room_000.map 512 512 486 477 108 33 777.436 +195 maps/rooms/64room_000.map 512 512 102 58 477 494 781.808 +195 maps/rooms/64room_000.map 512 512 486 490 16 69 782.879 +195 maps/rooms/64room_000.map 512 512 477 12 44 414 781.95 +195 maps/rooms/64room_000.map 512 512 93 53 497 506 781.909 +195 maps/rooms/64room_000.map 512 512 53 139 433 476 781.34 +195 maps/rooms/64room_000.map 512 512 327 470 22 188 781.382 +195 maps/rooms/64room_000.map 512 512 489 395 60 152 781.612 +195 maps/rooms/64room_000.map 512 512 435 487 12 7 782.637 +195 maps/rooms/64room_000.map 512 512 509 440 3 43 780.293 +195 maps/rooms/64room_000.map 512 512 489 38 30 485 781.879 +196 maps/rooms/64room_000.map 512 512 56 163 345 497 784.151 +196 maps/rooms/64room_000.map 512 512 22 507 503 50 785.293 +196 maps/rooms/64room_000.map 512 512 47 481 483 23 784.808 +196 maps/rooms/64room_000.map 512 512 49 180 420 449 785.151 +196 maps/rooms/64room_000.map 512 512 97 56 471 501 787.122 +196 maps/rooms/64room_000.map 512 512 18 191 413 498 786.281 +196 maps/rooms/64room_000.map 512 512 2 76 475 477 785.536 +196 maps/rooms/64room_000.map 512 512 496 5 48 409 784.423 +196 maps/rooms/64room_000.map 512 512 476 458 46 9 786.193 +196 maps/rooms/64room_000.map 512 512 429 494 51 147 786.11 +197 maps/rooms/64room_000.map 512 512 345 510 53 157 791.666 +197 maps/rooms/64room_000.map 512 512 444 456 46 150 789.068 +197 maps/rooms/64room_000.map 512 512 333 504 38 178 791.365 +197 maps/rooms/64room_000.map 512 512 57 3 497 469 788.566 +197 maps/rooms/64room_000.map 512 512 483 493 106 38 790.607 +197 maps/rooms/64room_000.map 512 512 464 423 56 187 789.193 +197 maps/rooms/64room_000.map 512 512 48 460 465 8 789.365 +197 maps/rooms/64room_000.map 512 512 478 471 107 14 790.406 +197 maps/rooms/64room_000.map 512 512 121 30 470 466 790.82 +197 maps/rooms/64room_000.map 512 512 341 499 43 181 788.122 +198 maps/rooms/64room_000.map 512 512 456 16 109 473 795.436 +198 maps/rooms/64room_000.map 512 512 438 468 60 146 792.926 +198 maps/rooms/64room_000.map 512 512 490 8 11 438 793.288 +198 maps/rooms/64room_000.map 512 512 53 31 491 499 794.323 +198 maps/rooms/64room_000.map 512 512 469 420 60 183 794.767 +198 maps/rooms/64room_000.map 512 512 452 27 60 459 793.151 +198 maps/rooms/64room_000.map 512 512 459 62 70 502 795.34 +198 maps/rooms/64room_000.map 512 512 88 479 462 10 795.708 +198 maps/rooms/64room_000.map 512 512 493 491 107 25 793.193 +198 maps/rooms/64room_000.map 512 512 84 26 449 471 793.779 +199 maps/rooms/64room_000.map 512 512 456 22 23 434 798.051 +199 maps/rooms/64room_000.map 512 512 97 481 485 2 796.151 +199 maps/rooms/64room_000.map 512 512 125 457 459 21 799.737 +199 maps/rooms/64room_000.map 512 512 14 92 470 506 797.98 +199 maps/rooms/64room_000.map 512 512 481 37 8 485 799.992 +199 maps/rooms/64room_000.map 512 512 443 486 1 12 799.151 +199 maps/rooms/64room_000.map 512 512 503 427 49 152 797.867 +199 maps/rooms/64room_000.map 512 512 58 504 480 30 796.909 +199 maps/rooms/64room_000.map 512 512 389 511 52 185 797.423 +199 maps/rooms/64room_000.map 512 512 449 31 78 483 797.524 +200 maps/rooms/64room_000.map 512 512 471 20 22 474 800.235 +200 maps/rooms/64room_000.map 512 512 125 21 460 455 803.992 +200 maps/rooms/64room_000.map 512 512 94 482 450 27 802.879 +200 maps/rooms/64room_000.map 512 512 13 155 499 473 801.009 +200 maps/rooms/64room_000.map 512 512 467 8 112 465 800.95 +200 maps/rooms/64room_000.map 512 512 502 12 7 453 801.696 +200 maps/rooms/64room_000.map 512 512 454 470 104 22 800.649 +200 maps/rooms/64room_000.map 512 512 456 464 118 28 801.82 +200 maps/rooms/64room_000.map 512 512 51 142 510 423 801.068 +200 maps/rooms/64room_000.map 512 512 452 8 38 410 801.585 +201 maps/rooms/64room_000.map 512 512 475 62 10 500 807.465 +201 maps/rooms/64room_000.map 512 512 56 53 451 484 807.82 +201 maps/rooms/64room_000.map 512 512 432 495 32 191 806.909 +201 maps/rooms/64room_000.map 512 512 52 6 453 452 807.222 +201 maps/rooms/64room_000.map 512 512 495 437 49 177 807.293 +201 maps/rooms/64room_000.map 512 512 79 504 480 6 806.009 +201 maps/rooms/64room_000.map 512 512 47 13 459 478 807.063 +201 maps/rooms/64room_000.map 512 512 462 40 46 494 804.566 +201 maps/rooms/64room_000.map 512 512 482 491 7 55 805.021 +201 maps/rooms/64room_000.map 512 512 487 447 49 178 804.436 +202 maps/rooms/64room_000.map 512 512 44 22 465 491 809.82 +202 maps/rooms/64room_000.map 512 512 1 500 486 43 808.063 +202 maps/rooms/64room_000.map 512 512 10 5 504 450 808.678 +202 maps/rooms/64room_000.map 512 512 454 463 23 55 811.749 +202 maps/rooms/64room_000.map 512 512 499 496 86 8 808.98 +202 maps/rooms/64room_000.map 512 512 12 154 469 475 809.051 +202 maps/rooms/64room_000.map 512 512 497 17 38 502 809.151 +202 maps/rooms/64room_000.map 512 512 478 471 29 155 810.536 +202 maps/rooms/64room_000.map 512 512 487 472 30 155 808.808 +202 maps/rooms/64room_000.map 512 512 470 500 59 18 811.607 +203 maps/rooms/64room_000.map 512 512 481 477 22 19 812.436 +203 maps/rooms/64room_000.map 512 512 496 509 55 18 813.98 +203 maps/rooms/64room_000.map 512 512 452 485 52 12 815.891 +203 maps/rooms/64room_000.map 512 512 467 482 31 54 814.649 +203 maps/rooms/64room_000.map 512 512 54 2 489 493 814.808 +203 maps/rooms/64room_000.map 512 512 470 488 105 10 813.891 +203 maps/rooms/64room_000.map 512 512 8 47 490 494 812.293 +203 maps/rooms/64room_000.map 512 512 462 43 54 506 812.009 +203 maps/rooms/64room_000.map 512 512 36 145 498 475 813.252 +203 maps/rooms/64room_000.map 512 512 496 505 48 17 813.879 diff --git a/node_modules/pathfinding/benchmark/scen/arena.map.scen b/node_modules/pathfinding/benchmark/scen/arena.map.scen new file mode 100644 index 0000000..d340aca --- /dev/null +++ b/node_modules/pathfinding/benchmark/scen/arena.map.scen @@ -0,0 +1,161 @@ +version 1 +0 maps/dao/arena.map 49 49 1 11 1 12 1 +0 maps/dao/arena.map 49 49 1 12 1 10 2 +0 maps/dao/arena.map 49 49 1 13 4 12 3.41421 +0 maps/dao/arena.map 49 49 1 3 3 1 3.41421 +0 maps/dao/arena.map 49 49 1 3 4 3 3 +0 maps/dao/arena.map 49 49 1 4 4 2 3.82843 +0 maps/dao/arena.map 49 49 1 40 2 39 1.41421 +0 maps/dao/arena.map 49 49 1 41 1 39 2 +0 maps/dao/arena.map 49 49 1 41 1 44 3 +0 maps/dao/arena.map 49 49 1 42 4 43 3.41421 +1 maps/dao/arena.map 49 49 1 10 7 10 6 +1 maps/dao/arena.map 49 49 1 11 1 4 7 +1 maps/dao/arena.map 49 49 1 11 7 14 7.24264 +1 maps/dao/arena.map 49 49 1 12 5 7 6.65685 +1 maps/dao/arena.map 49 49 1 12 6 15 6.24264 +1 maps/dao/arena.map 49 49 1 12 8 11 7.41421 +1 maps/dao/arena.map 49 49 1 14 1 9 5 +1 maps/dao/arena.map 49 49 1 24 7 26 6.82843 +1 maps/dao/arena.map 49 49 1 25 5 25 4 +1 maps/dao/arena.map 49 49 1 35 5 33 4.82843 +2 maps/dao/arena.map 49 49 1 11 4 18 8.24264 +2 maps/dao/arena.map 49 49 1 12 12 14 11.8284 +2 maps/dao/arena.map 49 49 1 13 4 23 11.8284 +2 maps/dao/arena.map 49 49 1 13 5 3 11.6569 +2 maps/dao/arena.map 49 49 1 13 6 7 8.07107 +2 maps/dao/arena.map 49 49 1 13 7 7 8.48528 +2 maps/dao/arena.map 49 49 1 23 7 32 11.4853 +2 maps/dao/arena.map 49 49 1 24 11 25 10.4142 +2 maps/dao/arena.map 49 49 1 24 6 32 10.0711 +2 maps/dao/arena.map 49 49 1 25 9 24 8.41421 +3 maps/dao/arena.map 49 49 1 10 11 19 13.7279 +3 maps/dao/arena.map 49 49 1 10 13 11 12.4142 +3 maps/dao/arena.map 49 49 1 11 10 2 12.7279 +3 maps/dao/arena.map 49 49 1 12 11 21 13.7279 +3 maps/dao/arena.map 49 49 1 12 13 13 12.4142 +3 maps/dao/arena.map 49 49 1 12 14 12 13 +3 maps/dao/arena.map 49 49 1 12 6 25 15.0711 +3 maps/dao/arena.map 49 49 1 13 11 3 14.1421 +3 maps/dao/arena.map 49 49 1 13 13 11 12.8284 +3 maps/dao/arena.map 49 49 1 14 6 23 12.2426 +4 maps/dao/arena.map 49 49 1 10 18 11 17.4142 +4 maps/dao/arena.map 49 49 1 11 16 14 16.2426 +4 maps/dao/arena.map 49 49 1 12 14 2 17.1421 +4 maps/dao/arena.map 49 49 1 12 17 13 16.4142 +4 maps/dao/arena.map 49 49 1 12 9 28 19.3137 +4 maps/dao/arena.map 49 49 1 13 4 30 18.8284 +4 maps/dao/arena.map 49 49 1 13 9 26 16.8995 +4 maps/dao/arena.map 49 49 1 14 14 22 16.3137 +4 maps/dao/arena.map 49 49 1 23 10 8 19.3137 +4 maps/dao/arena.map 49 49 1 23 14 9 19.9706 +5 maps/dao/arena.map 49 49 1 10 13 29 23.9706 +5 maps/dao/arena.map 49 49 1 10 18 22 21.9706 +5 maps/dao/arena.map 49 49 1 10 19 18 22.1421 +5 maps/dao/arena.map 49 49 1 10 21 2 23.3137 +5 maps/dao/arena.map 49 49 1 10 5 32 23.6569 +5 maps/dao/arena.map 49 49 1 10 6 29 21.0711 +5 maps/dao/arena.map 49 49 1 11 20 7 20.6569 +5 maps/dao/arena.map 49 49 1 11 21 17 23.0711 +5 maps/dao/arena.map 49 49 1 11 22 16 23.0711 +5 maps/dao/arena.map 49 49 1 11 8 29 20.8995 +6 maps/dao/arena.map 49 49 1 10 22 22 25.9706 +6 maps/dao/arena.map 49 49 1 10 5 33 24.6569 +6 maps/dao/arena.map 49 49 1 11 10 32 24.7279 +6 maps/dao/arena.map 49 49 1 11 20 31 27.8701 +6 maps/dao/arena.map 49 49 1 11 21 23 24.9706 +6 maps/dao/arena.map 49 49 1 11 24 14 24.2426 +6 maps/dao/arena.map 49 49 1 11 25 4 26.8995 +6 maps/dao/arena.map 49 49 1 11 3 36 25.8284 +6 maps/dao/arena.map 49 49 1 12 19 27 24.2132 +6 maps/dao/arena.map 49 49 1 12 2 37 26.2426 +7 maps/dao/arena.map 49 49 1 10 22 31 29.6985 +7 maps/dao/arena.map 49 49 1 10 24 27 30.0416 +7 maps/dao/arena.map 49 49 1 10 28 15 29.0711 +7 maps/dao/arena.map 49 49 1 10 7 39 31.4853 +7 maps/dao/arena.map 49 49 1 11 12 35 28.5563 +7 maps/dao/arena.map 49 49 1 11 28 18 29.8995 +7 maps/dao/arena.map 49 49 1 11 5 40 30.6569 +7 maps/dao/arena.map 49 49 1 12 26 3 28.7279 +7 maps/dao/arena.map 49 49 1 12 29 14 28.8284 +7 maps/dao/arena.map 49 49 1 12 29 6 30.4853 +8 maps/dao/arena.map 49 49 1 10 25 36 35.9411 +8 maps/dao/arena.map 49 49 1 10 27 25 32.2132 +8 maps/dao/arena.map 49 49 1 10 32 4 33.4853 +8 maps/dao/arena.map 49 49 1 10 33 4 34.4853 +8 maps/dao/arena.map 49 49 1 11 10 42 34.7279 +8 maps/dao/arena.map 49 49 1 11 27 28 33.0416 +8 maps/dao/arena.map 49 49 1 11 30 2 32.7279 +8 maps/dao/arena.map 49 49 1 11 31 3 33.3137 +8 maps/dao/arena.map 49 49 1 11 5 42 32.6569 +8 maps/dao/arena.map 49 49 1 12 18 37 32.8701 +9 maps/dao/arena.map 49 49 1 10 15 43 38.799 +9 maps/dao/arena.map 49 49 1 10 21 41 39.2843 +9 maps/dao/arena.map 49 49 1 10 27 37 37.7696 +9 maps/dao/arena.map 49 49 1 10 29 38 39.598 +9 maps/dao/arena.map 49 49 1 10 31 25 36.2132 +9 maps/dao/arena.map 49 49 1 10 38 13 38.2426 +9 maps/dao/arena.map 49 49 1 10 38 6 38.6569 +9 maps/dao/arena.map 49 49 1 10 39 6 39.6569 +9 maps/dao/arena.map 49 49 1 10 40 9 39.4142 +9 maps/dao/arena.map 49 49 1 11 11 43 36.1421 +10 maps/dao/arena.map 49 49 1 10 12 47 41.5563 +10 maps/dao/arena.map 49 49 1 10 14 47 42.3848 +10 maps/dao/arena.map 49 49 1 10 16 46 42.2132 +10 maps/dao/arena.map 49 49 1 10 28 41 42.1838 +10 maps/dao/arena.map 49 49 1 10 37 21 40.5563 +10 maps/dao/arena.map 49 49 1 10 39 24 43.799 +10 maps/dao/arena.map 49 49 1 11 16 45 40.2132 +10 maps/dao/arena.map 49 49 1 11 21 43 40.2843 +10 maps/dao/arena.map 49 49 1 11 32 39 42.598 +10 maps/dao/arena.map 49 49 1 11 34 29 40.4558 +11 maps/dao/arena.map 49 49 1 10 29 43 44.598 +11 maps/dao/arena.map 49 49 1 10 43 15 44.0711 +11 maps/dao/arena.map 49 49 1 10 43 17 44.8995 +11 maps/dao/arena.map 49 49 1 10 45 10 44 +11 maps/dao/arena.map 49 49 1 10 46 15 47.0711 +11 maps/dao/arena.map 49 49 1 10 46 3 47.8995 +11 maps/dao/arena.map 49 49 1 11 30 45 46.0122 +11 maps/dao/arena.map 49 49 1 11 35 41 46.4264 +11 maps/dao/arena.map 49 49 1 11 35 42 46.8406 +11 maps/dao/arena.map 49 49 1 11 43 3 45.3137 +12 maps/dao/arena.map 49 49 1 10 31 46 48.4264 +12 maps/dao/arena.map 49 49 1 10 34 46 49.669 +12 maps/dao/arena.map 49 49 1 10 35 46 50.0833 +12 maps/dao/arena.map 49 49 1 10 36 42 48.2548 +12 maps/dao/arena.map 49 49 1 10 38 45 51.4975 +12 maps/dao/arena.map 49 49 1 10 46 18 48.3137 +12 maps/dao/arena.map 49 49 1 11 37 44 49.669 +12 maps/dao/arena.map 49 49 1 11 41 35 49.9411 +12 maps/dao/arena.map 49 49 1 11 43 27 48.6274 +12 maps/dao/arena.map 49 49 1 11 44 25 48.799 +13 maps/dao/arena.map 49 49 1 10 41 40 52.4264 +13 maps/dao/arena.map 49 49 1 10 43 40 54.4264 +13 maps/dao/arena.map 49 49 1 11 39 47 52.9117 +13 maps/dao/arena.map 49 49 1 11 42 46 55.4975 +13 maps/dao/arena.map 49 49 1 11 45 33 53.1127 +13 maps/dao/arena.map 49 49 1 12 43 43 54.8406 +13 maps/dao/arena.map 49 49 1 12 44 38 53.7696 +13 maps/dao/arena.map 49 49 1 12 46 34 54.1127 +13 maps/dao/arena.map 49 49 1 13 42 40 52.1838 +13 maps/dao/arena.map 49 49 1 14 46 32 52.4558 +14 maps/dao/arena.map 49 49 1 14 44 46 56.2548 +14 maps/dao/arena.map 49 49 1 14 46 43 57.0122 +14 maps/dao/arena.map 49 49 1 35 46 3 58.2548 +14 maps/dao/arena.map 49 49 1 37 43 1 56.9117 +14 maps/dao/arena.map 49 49 1 38 43 3 56.4975 +14 maps/dao/arena.map 49 49 1 38 47 13 56.3553 +14 maps/dao/arena.map 49 49 1 39 47 14 56.3553 +14 maps/dao/arena.map 49 49 1 4 38 47 58.3259 +14 maps/dao/arena.map 49 49 1 4 41 42 56.9117 +14 maps/dao/arena.map 49 49 1 42 44 5 58.3259 +15 maps/dao/arena.map 49 49 1 3 41 47 60.5685 +15 maps/dao/arena.map 49 49 1 3 47 37 60.0833 +15 maps/dao/arena.map 49 49 1 39 46 1 60.7401 +15 maps/dao/arena.map 49 49 1 4 43 46 60.5685 +15 maps/dao/arena.map 49 49 1 4 44 45 61.1543 +15 maps/dao/arena.map 49 49 1 40 47 3 61.3259 +15 maps/dao/arena.map 49 49 1 41 46 2 61.1543 +15 maps/dao/arena.map 49 49 1 45 47 9 60.9117 +15 maps/dao/arena.map 49 49 1 7 47 44 61.3259 +15 maps/dao/arena.map 49 49 1 7 47 46 62.1543 diff --git a/node_modules/pathfinding/benchmark/scen/lak304d.map.scen b/node_modules/pathfinding/benchmark/scen/lak304d.map.scen new file mode 100644 index 0000000..73c74be --- /dev/null +++ b/node_modules/pathfinding/benchmark/scen/lak304d.map.scen @@ -0,0 +1,774 @@ +version 1 +0 maps/dao/lak304d.map 193 194 10 115 7 116 3.41421 +0 maps/dao/lak304d.map 193 194 10 66 13 65 3.41421 +0 maps/dao/lak304d.map 193 194 10 88 12 90 3.41421 +0 maps/dao/lak304d.map 193 194 100 43 97 42 3.41421 +0 maps/dao/lak304d.map 193 194 100 98 102 95 3.82843 +0 maps/dao/lak304d.map 193 194 101 109 101 109 0 +0 maps/dao/lak304d.map 193 194 101 113 101 111 2 +0 maps/dao/lak304d.map 193 194 101 44 98 45 3.41421 +0 maps/dao/lak304d.map 193 194 101 91 100 94 3.41421 +0 maps/dao/lak304d.map 193 194 103 101 101 101 2 +1 maps/dao/lak304d.map 193 194 10 68 6 66 4.82843 +1 maps/dao/lak304d.map 193 194 10 70 5 73 6.24264 +1 maps/dao/lak304d.map 193 194 100 115 96 116 4.41421 +1 maps/dao/lak304d.map 193 194 100 118 105 119 5.41421 +1 maps/dao/lak304d.map 193 194 100 127 96 125 4.82843 +1 maps/dao/lak304d.map 193 194 100 46 101 51 5.41421 +1 maps/dao/lak304d.map 193 194 101 121 98 124 4.24264 +1 maps/dao/lak304d.map 193 194 101 141 107 142 6.41421 +1 maps/dao/lak304d.map 193 194 101 42 101 47 5 +1 maps/dao/lak304d.map 193 194 101 91 107 89 6.82843 +2 maps/dao/lak304d.map 193 194 1 82 3 89 9.24264 +2 maps/dao/lak304d.map 193 194 100 116 107 107 11.8995 +2 maps/dao/lak304d.map 193 194 100 146 110 146 10 +2 maps/dao/lak304d.map 193 194 100 148 103 141 8.24264 +2 maps/dao/lak304d.map 193 194 100 167 110 170 11.2426 +2 maps/dao/lak304d.map 193 194 100 176 109 177 9.41421 +2 maps/dao/lak304d.map 193 194 100 82 98 92 11.4142 +2 maps/dao/lak304d.map 193 194 100 90 108 84 10.4853 +2 maps/dao/lak304d.map 193 194 101 113 108 121 10.8995 +2 maps/dao/lak304d.map 193 194 101 172 99 163 9.82843 +3 maps/dao/lak304d.map 193 194 10 117 12 103 14.8284 +3 maps/dao/lak304d.map 193 194 10 67 17 56 13.8995 +3 maps/dao/lak304d.map 193 194 10 70 1 81 14.7279 +3 maps/dao/lak304d.map 193 194 100 126 91 124 13.4853 +3 maps/dao/lak304d.map 193 194 100 174 115 172 15.8284 +3 maps/dao/lak304d.map 193 194 100 175 110 182 14.0711 +3 maps/dao/lak304d.map 193 194 100 73 107 72 15.6569 +3 maps/dao/lak304d.map 193 194 100 77 90 87 14.1421 +3 maps/dao/lak304d.map 193 194 100 97 105 110 15.0711 +3 maps/dao/lak304d.map 193 194 101 100 90 107 13.8995 +4 maps/dao/lak304d.map 193 194 100 103 87 117 19.3848 +4 maps/dao/lak304d.map 193 194 100 105 94 121 18.4853 +4 maps/dao/lak304d.map 193 194 100 112 83 105 19.8995 +4 maps/dao/lak304d.map 193 194 100 118 87 108 17.1421 +4 maps/dao/lak304d.map 193 194 100 124 115 127 16.2426 +4 maps/dao/lak304d.map 193 194 100 166 99 182 16.4142 +4 maps/dao/lak304d.map 193 194 100 175 104 160 16.6569 +4 maps/dao/lak304d.map 193 194 100 181 115 169 19.9706 +4 maps/dao/lak304d.map 193 194 100 72 88 85 17.9706 +4 maps/dao/lak304d.map 193 194 100 82 109 89 16.8284 +5 maps/dao/lak304d.map 193 194 1 115 12 132 21.5563 +5 maps/dao/lak304d.map 193 194 10 117 29 118 20.2426 +5 maps/dao/lak304d.map 193 194 100 101 93 80 23.8995 +5 maps/dao/lak304d.map 193 194 100 105 97 85 21.2426 +5 maps/dao/lak304d.map 193 194 100 106 82 114 21.3137 +5 maps/dao/lak304d.map 193 194 100 107 102 129 22.8284 +5 maps/dao/lak304d.map 193 194 100 119 79 112 23.8995 +5 maps/dao/lak304d.map 193 194 100 122 83 108 22.799 +5 maps/dao/lak304d.map 193 194 100 147 81 143 20.6569 +5 maps/dao/lak304d.map 193 194 100 38 116 49 20.5563 +6 maps/dao/lak304d.map 193 194 1 78 25 70 27.3137 +6 maps/dao/lak304d.map 193 194 10 122 19 104 24.6569 +6 maps/dao/lak304d.map 193 194 10 62 28 50 25.3137 +6 maps/dao/lak304d.map 193 194 10 66 30 57 25.4853 +6 maps/dao/lak304d.map 193 194 100 182 122 168 27.799 +6 maps/dao/lak304d.map 193 194 100 40 77 48 26.3137 +6 maps/dao/lak304d.map 193 194 100 92 125 91 25.4142 +6 maps/dao/lak304d.map 193 194 101 162 109 184 26.4853 +6 maps/dao/lak304d.map 193 194 101 87 74 87 27.8284 +6 maps/dao/lak304d.map 193 194 101 89 108 114 27.8995 +7 maps/dao/lak304d.map 193 194 1 82 23 62 30.8701 +7 maps/dao/lak304d.map 193 194 10 125 24 149 29.799 +7 maps/dao/lak304d.map 193 194 10 126 28 105 29.0416 +7 maps/dao/lak304d.map 193 194 10 128 4 102 29.6569 +7 maps/dao/lak304d.map 193 194 10 61 16 89 30.4853 +7 maps/dao/lak304d.map 193 194 10 94 13 65 31.8995 +7 maps/dao/lak304d.map 193 194 100 103 98 75 28.8284 +7 maps/dao/lak304d.map 193 194 100 107 78 125 30.6274 +7 maps/dao/lak304d.map 193 194 100 125 71 118 31.8995 +7 maps/dao/lak304d.map 193 194 100 147 76 157 28.1421 +8 maps/dao/lak304d.map 193 194 10 121 25 147 32.2132 +8 maps/dao/lak304d.map 193 194 10 77 36 62 33.9706 +8 maps/dao/lak304d.map 193 194 10 83 28 60 33.9706 +8 maps/dao/lak304d.map 193 194 100 107 86 135 33.799 +8 maps/dao/lak304d.map 193 194 100 114 90 84 34.1421 +8 maps/dao/lak304d.map 193 194 100 122 102 88 34.8284 +8 maps/dao/lak304d.map 193 194 100 124 75 102 34.1127 +8 maps/dao/lak304d.map 193 194 100 127 75 106 34.2843 +8 maps/dao/lak304d.map 193 194 100 152 128 140 32.9706 +8 maps/dao/lak304d.map 193 194 100 73 112 103 35.799 +9 maps/dao/lak304d.map 193 194 10 61 6 94 36.3137 +9 maps/dao/lak304d.map 193 194 10 75 20 92 37.7279 +9 maps/dao/lak304d.map 193 194 100 106 122 77 38.1127 +9 maps/dao/lak304d.map 193 194 100 126 64 117 39.7279 +9 maps/dao/lak304d.map 193 194 100 136 112 102 38.9706 +9 maps/dao/lak304d.map 193 194 100 136 91 101 38.7279 +9 maps/dao/lak304d.map 193 194 100 74 116 71 39.3848 +9 maps/dao/lak304d.map 193 194 101 109 109 75 39.5563 +9 maps/dao/lak304d.map 193 194 101 117 85 86 39.3848 +9 maps/dao/lak304d.map 193 194 101 127 88 96 36.3848 +10 maps/dao/lak304d.map 193 194 1 81 23 51 43.4558 +10 maps/dao/lak304d.map 193 194 10 117 29 152 42.8701 +10 maps/dao/lak304d.map 193 194 10 118 23 155 43.2132 +10 maps/dao/lak304d.map 193 194 10 93 18 55 42.9706 +10 maps/dao/lak304d.map 193 194 100 102 68 88 40.1421 +10 maps/dao/lak304d.map 193 194 100 109 86 71 43.799 +10 maps/dao/lak304d.map 193 194 100 117 124 86 40.9411 +10 maps/dao/lak304d.map 193 194 100 121 110 85 40.1421 +10 maps/dao/lak304d.map 193 194 100 136 73 123 42.3848 +10 maps/dao/lak304d.map 193 194 100 46 77 22 40.5563 +11 maps/dao/lak304d.map 193 194 10 109 29 147 45.8701 +11 maps/dao/lak304d.map 193 194 10 68 53 80 47.9706 +11 maps/dao/lak304d.map 193 194 10 77 45 53 47.8701 +11 maps/dao/lak304d.map 193 194 10 78 45 77 44.3848 +11 maps/dao/lak304d.map 193 194 100 104 81 68 45.0416 +11 maps/dao/lak304d.map 193 194 100 113 135 84 47.598 +11 maps/dao/lak304d.map 193 194 100 114 78 82 44.6274 +11 maps/dao/lak304d.map 193 194 100 134 98 89 45.8284 +11 maps/dao/lak304d.map 193 194 100 146 61 167 47.6985 +11 maps/dao/lak304d.map 193 194 100 148 63 132 44.799 +12 maps/dao/lak304d.map 193 194 1 114 42 137 50.5269 +12 maps/dao/lak304d.map 193 194 1 92 31 58 49.9411 +12 maps/dao/lak304d.map 193 194 10 66 44 93 49.2843 +12 maps/dao/lak304d.map 193 194 10 83 27 40 50.6274 +12 maps/dao/lak304d.map 193 194 10 88 38 81 49.6274 +12 maps/dao/lak304d.map 193 194 100 114 139 87 50.1838 +12 maps/dao/lak304d.map 193 194 100 119 124 80 48.9411 +12 maps/dao/lak304d.map 193 194 100 136 65 115 49.5563 +12 maps/dao/lak304d.map 193 194 100 155 137 122 50.669 +12 maps/dao/lak304d.map 193 194 100 79 98 127 48.8284 +13 maps/dao/lak304d.map 193 194 10 115 43 150 52.1838 +13 maps/dao/lak304d.map 193 194 10 81 45 90 52.8701 +13 maps/dao/lak304d.map 193 194 10 94 25 88 54.5563 +13 maps/dao/lak304d.map 193 194 100 117 50 113 55.799 +13 maps/dao/lak304d.map 193 194 100 123 74 86 55.9706 +13 maps/dao/lak304d.map 193 194 100 148 145 125 54.5269 +13 maps/dao/lak304d.map 193 194 100 149 69 183 54.4558 +13 maps/dao/lak304d.map 193 194 100 44 52 62 55.4558 +13 maps/dao/lak304d.map 193 194 100 78 61 108 55.5269 +13 maps/dao/lak304d.map 193 194 101 120 114 71 54.3848 +14 maps/dao/lak304d.map 193 194 10 124 53 131 56.6274 +14 maps/dao/lak304d.map 193 194 10 72 58 68 56.2843 +14 maps/dao/lak304d.map 193 194 10 76 50 100 59.9411 +14 maps/dao/lak304d.map 193 194 10 79 51 44 59.598 +14 maps/dao/lak304d.map 193 194 10 81 50 47 59.3553 +14 maps/dao/lak304d.map 193 194 10 82 46 95 59.2843 +14 maps/dao/lak304d.map 193 194 100 125 73 89 57.7279 +14 maps/dao/lak304d.map 193 194 100 127 127 82 56.1838 +14 maps/dao/lak304d.map 193 194 100 130 93 74 58.8995 +14 maps/dao/lak304d.map 193 194 100 154 91 186 56.3137 +15 maps/dao/lak304d.map 193 194 1 82 27 33 60.3553 +15 maps/dao/lak304d.map 193 194 10 55 52 68 60.0122 +15 maps/dao/lak304d.map 193 194 100 112 45 121 63.799 +15 maps/dao/lak304d.map 193 194 100 131 91 72 62.7279 +15 maps/dao/lak304d.map 193 194 100 135 79 92 62.9706 +15 maps/dao/lak304d.map 193 194 100 163 151 135 63.1838 +15 maps/dao/lak304d.map 193 194 100 176 150 167 63.5269 +15 maps/dao/lak304d.map 193 194 100 46 50 74 61.598 +15 maps/dao/lak304d.map 193 194 100 47 48 71 61.9411 +15 maps/dao/lak304d.map 193 194 100 76 113 132 62.2132 +16 maps/dao/lak304d.map 193 194 10 123 46 172 64.4975 +16 maps/dao/lak304d.map 193 194 10 128 59 125 65.9411 +16 maps/dao/lak304d.map 193 194 10 76 60 61 64.0122 +16 maps/dao/lak304d.map 193 194 100 104 145 103 66.7696 +16 maps/dao/lak304d.map 193 194 100 118 144 71 66.9828 +16 maps/dao/lak304d.map 193 194 100 154 47 151 67.1127 +16 maps/dao/lak304d.map 193 194 100 155 140 109 65.4975 +16 maps/dao/lak304d.map 193 194 101 101 47 121 65.2132 +16 maps/dao/lak304d.map 193 194 101 108 51 89 67.4853 +16 maps/dao/lak304d.map 193 194 101 112 56 125 66.7279 +17 maps/dao/lak304d.map 193 194 10 119 71 142 70.5269 +17 maps/dao/lak304d.map 193 194 100 104 50 87 68.0711 +17 maps/dao/lak304d.map 193 194 100 106 128 63 70.2548 +17 maps/dao/lak304d.map 193 194 100 112 133 62 71.669 +17 maps/dao/lak304d.map 193 194 100 129 52 122 70.6985 +17 maps/dao/lak304d.map 193 194 100 133 47 103 69.5269 +17 maps/dao/lak304d.map 193 194 100 141 55 113 70.9411 +17 maps/dao/lak304d.map 193 194 100 163 146 126 70.9411 +17 maps/dao/lak304d.map 193 194 100 82 127 62 70.799 +17 maps/dao/lak304d.map 193 194 100 94 44 90 71.6985 +18 maps/dao/lak304d.map 193 194 10 104 58 152 74.9117 +18 maps/dao/lak304d.map 193 194 10 64 62 50 75.4975 +18 maps/dao/lak304d.map 193 194 10 74 62 105 74.598 +18 maps/dao/lak304d.map 193 194 10 79 51 109 72.3553 +18 maps/dao/lak304d.map 193 194 100 101 146 110 72.1127 +18 maps/dao/lak304d.map 193 194 100 102 137 54 73.8701 +18 maps/dao/lak304d.map 193 194 100 135 52 119 73.6985 +18 maps/dao/lak304d.map 193 194 100 152 167 143 74.0416 +18 maps/dao/lak304d.map 193 194 100 51 52 90 74.3553 +18 maps/dao/lak304d.map 193 194 100 80 46 119 74.2548 +19 maps/dao/lak304d.map 193 194 1 112 64 131 77.4975 +19 maps/dao/lak304d.map 193 194 10 63 55 115 77.0833 +19 maps/dao/lak304d.map 193 194 10 94 59 68 79.7696 +19 maps/dao/lak304d.map 193 194 100 105 164 81 79.4975 +19 maps/dao/lak304d.map 193 194 100 106 152 61 79.669 +19 maps/dao/lak304d.map 193 194 100 149 162 110 78.1543 +19 maps/dao/lak304d.map 193 194 100 151 144 170 77.5269 +19 maps/dao/lak304d.map 193 194 100 155 152 101 78.468 +19 maps/dao/lak304d.map 193 194 100 161 148 121 76.7696 +19 maps/dao/lak304d.map 193 194 100 164 164 150 78.2843 +20 maps/dao/lak304d.map 193 194 10 88 60 42 80.669 +20 maps/dao/lak304d.map 193 194 100 101 163 86 82.4264 +20 maps/dao/lak304d.map 193 194 100 106 62 138 80.3848 +20 maps/dao/lak304d.map 193 194 100 107 53 142 80.2426 +20 maps/dao/lak304d.map 193 194 100 115 134 54 80.4975 +20 maps/dao/lak304d.map 193 194 100 119 146 57 82.8112 +20 maps/dao/lak304d.map 193 194 100 124 144 104 80.5685 +20 maps/dao/lak304d.map 193 194 100 143 33 161 81.7696 +20 maps/dao/lak304d.map 193 194 100 146 26 127 81.8701 +20 maps/dao/lak304d.map 193 194 100 149 59 103 80.8406 +21 maps/dao/lak304d.map 193 194 10 64 65 119 87.1543 +21 maps/dao/lak304d.map 193 194 10 70 73 113 87.2548 +21 maps/dao/lak304d.map 193 194 10 70 75 104 87.1838 +21 maps/dao/lak304d.map 193 194 100 106 34 76 84.8701 +21 maps/dao/lak304d.map 193 194 100 118 138 113 86.0538 +21 maps/dao/lak304d.map 193 194 100 144 27 121 84.5269 +21 maps/dao/lak304d.map 193 194 100 153 169 117 86.397 +21 maps/dao/lak304d.map 193 194 100 154 122 175 87.9117 +21 maps/dao/lak304d.map 193 194 100 81 155 50 86.5269 +21 maps/dao/lak304d.map 193 194 100 89 168 50 87.669 +22 maps/dao/lak304d.map 193 194 10 105 74 148 89.4264 +22 maps/dao/lak304d.map 193 194 10 114 48 106 89.0122 +22 maps/dao/lak304d.map 193 194 100 108 57 66 91.9706 +22 maps/dao/lak304d.map 193 194 100 116 159 116 90.0538 +22 maps/dao/lak304d.map 193 194 100 135 151 102 89.9828 +22 maps/dao/lak304d.map 193 194 100 151 23 158 89.8406 +22 maps/dao/lak304d.map 193 194 100 152 67 105 88.669 +22 maps/dao/lak304d.map 193 194 100 161 103 144 91.9411 +22 maps/dao/lak304d.map 193 194 100 168 108 146 89.8406 +22 maps/dao/lak304d.map 193 194 100 170 169 156 88.8406 +23 maps/dao/lak304d.map 193 194 1 78 70 111 94.9117 +23 maps/dao/lak304d.map 193 194 1 82 68 106 92.4975 +23 maps/dao/lak304d.map 193 194 1 89 53 114 92.4975 +23 maps/dao/lak304d.map 193 194 10 124 91 153 93.0122 +23 maps/dao/lak304d.map 193 194 10 63 83 49 92.0538 +23 maps/dao/lak304d.map 193 194 10 65 86 46 95.468 +23 maps/dao/lak304d.map 193 194 10 74 63 128 93.0833 +23 maps/dao/lak304d.map 193 194 100 100 42 135 92.2132 +23 maps/dao/lak304d.map 193 194 100 110 179 69 95.9828 +23 maps/dao/lak304d.map 193 194 100 110 71 149 95.1127 +24 maps/dao/lak304d.map 193 194 1 115 88 143 98.598 +24 maps/dao/lak304d.map 193 194 1 92 45 120 97.598 +24 maps/dao/lak304d.map 193 194 10 104 43 109 98.0833 +24 maps/dao/lak304d.map 193 194 10 125 68 119 98.7696 +24 maps/dao/lak304d.map 193 194 10 128 70 158 96.669 +24 maps/dao/lak304d.map 193 194 10 55 61 123 97.3259 +24 maps/dao/lak304d.map 193 194 10 65 78 34 99.3675 +24 maps/dao/lak304d.map 193 194 10 73 84 33 99.5391 +24 maps/dao/lak304d.map 193 194 10 90 73 50 97.2254 +24 maps/dao/lak304d.map 193 194 10 92 73 51 99.397 +25 maps/dao/lak304d.map 193 194 10 103 58 107 100.184 +25 maps/dao/lak304d.map 193 194 10 72 47 141 103.598 +25 maps/dao/lak304d.map 193 194 10 83 74 123 102.225 +25 maps/dao/lak304d.map 193 194 100 105 149 33 101.083 +25 maps/dao/lak304d.map 193 194 100 109 185 82 101.983 +25 maps/dao/lak304d.map 193 194 100 109 19 86 101.698 +25 maps/dao/lak304d.map 193 194 100 112 141 33 103.983 +25 maps/dao/lak304d.map 193 194 100 115 20 82 100.941 +25 maps/dao/lak304d.map 193 194 100 118 168 121 102.539 +25 maps/dao/lak304d.map 193 194 100 125 175 73 101.225 +26 maps/dao/lak304d.map 193 194 1 116 67 112 106.426 +26 maps/dao/lak304d.map 193 194 10 124 75 121 105.841 +26 maps/dao/lak304d.map 193 194 10 60 46 139 107.912 +26 maps/dao/lak304d.map 193 194 10 68 48 146 107.255 +26 maps/dao/lak304d.map 193 194 10 70 68 140 104.569 +26 maps/dao/lak304d.map 193 194 10 71 63 143 105.083 +26 maps/dao/lak304d.map 193 194 10 71 94 103 106.184 +26 maps/dao/lak304d.map 193 194 10 72 91 102 104.012 +26 maps/dao/lak304d.map 193 194 100 103 141 27 106.255 +26 maps/dao/lak304d.map 193 194 100 103 32 158 107.184 +27 maps/dao/lak304d.map 193 194 1 113 69 161 111.64 +27 maps/dao/lak304d.map 193 194 1 78 85 116 111.983 +27 maps/dao/lak304d.map 193 194 10 117 53 83 110.012 +27 maps/dao/lak304d.map 193 194 10 117 79 114 109.841 +27 maps/dao/lak304d.map 193 194 10 121 44 81 111.598 +27 maps/dao/lak304d.map 193 194 10 62 77 26 109.024 +27 maps/dao/lak304d.map 193 194 10 66 95 99 110.912 +27 maps/dao/lak304d.map 193 194 10 71 99 39 108.882 +27 maps/dao/lak304d.map 193 194 10 73 72 144 110.64 +27 maps/dao/lak304d.map 193 194 10 77 87 26 111.196 +28 maps/dao/lak304d.map 193 194 1 80 75 29 115.853 +28 maps/dao/lak304d.map 193 194 1 82 68 137 114.711 +28 maps/dao/lak304d.map 193 194 10 102 71 164 114.64 +28 maps/dao/lak304d.map 193 194 10 111 79 115 115.669 +28 maps/dao/lak304d.map 193 194 10 112 74 174 113.397 +28 maps/dao/lak304d.map 193 194 10 63 94 116 112.397 +28 maps/dao/lak304d.map 193 194 10 69 98 117 114.326 +28 maps/dao/lak304d.map 193 194 10 74 87 128 113.569 +28 maps/dao/lak304d.map 193 194 10 83 90 111 113.255 +28 maps/dao/lak304d.map 193 194 10 90 90 47 115.468 +29 maps/dao/lak304d.map 193 194 1 112 104 141 118.326 +29 maps/dao/lak304d.map 193 194 1 114 64 164 117.468 +29 maps/dao/lak304d.map 193 194 1 79 87 120 116.64 +29 maps/dao/lak304d.map 193 194 10 108 41 86 117.912 +29 maps/dao/lak304d.map 193 194 10 79 39 146 119.497 +29 maps/dao/lak304d.map 193 194 100 102 6 78 119.497 +29 maps/dao/lak304d.map 193 194 100 105 125 144 116.468 +29 maps/dao/lak304d.map 193 194 100 109 18 144 117.042 +29 maps/dao/lak304d.map 193 194 100 110 179 137 116.267 +29 maps/dao/lak304d.map 193 194 100 110 47 48 119.912 +30 maps/dao/lak304d.map 193 194 1 79 82 20 123.196 +30 maps/dao/lak304d.map 193 194 1 81 65 145 121.054 +30 maps/dao/lak304d.map 193 194 10 106 74 128 123.983 +30 maps/dao/lak304d.map 193 194 10 106 77 121 121.154 +30 maps/dao/lak304d.map 193 194 10 111 78 128 120.64 +30 maps/dao/lak304d.map 193 194 10 117 92 108 120.355 +30 maps/dao/lak304d.map 193 194 10 120 91 122 123.912 +30 maps/dao/lak304d.map 193 194 10 122 122 141 123.184 +30 maps/dao/lak304d.map 193 194 10 67 101 87 121.468 +30 maps/dao/lak304d.map 193 194 10 68 37 156 121.811 +31 maps/dao/lak304d.map 193 194 1 79 36 140 126.083 +31 maps/dao/lak304d.map 193 194 1 82 97 114 124.811 +31 maps/dao/lak304d.map 193 194 1 91 92 112 127.397 +31 maps/dao/lak304d.map 193 194 1 92 96 44 126.782 +31 maps/dao/lak304d.map 193 194 10 103 110 149 126.669 +31 maps/dao/lak304d.map 193 194 10 110 43 76 125.083 +31 maps/dao/lak304d.map 193 194 10 121 57 66 127.012 +31 maps/dao/lak304d.map 193 194 10 123 92 191 125.983 +31 maps/dao/lak304d.map 193 194 10 72 94 78 124.569 +31 maps/dao/lak304d.map 193 194 10 76 83 153 127.196 +32 maps/dao/lak304d.map 193 194 1 90 82 21 130.853 +32 maps/dao/lak304d.map 193 194 10 109 35 76 129.397 +32 maps/dao/lak304d.map 193 194 10 122 59 62 131.426 +32 maps/dao/lak304d.map 193 194 10 61 36 122 130.397 +32 maps/dao/lak304d.map 193 194 10 62 111 95 130.225 +32 maps/dao/lak304d.map 193 194 10 66 110 120 128.811 +32 maps/dao/lak304d.map 193 194 10 69 89 5 129.61 +32 maps/dao/lak304d.map 193 194 10 72 76 93 128.983 +32 maps/dao/lak304d.map 193 194 10 73 116 103 129.012 +32 maps/dao/lak304d.map 193 194 10 79 31 150 129.154 +33 maps/dao/lak304d.map 193 194 1 116 91 93 135.569 +33 maps/dao/lak304d.map 193 194 1 89 82 18 133.439 +33 maps/dao/lak304d.map 193 194 1 91 90 125 132.539 +33 maps/dao/lak304d.map 193 194 10 71 111 133 133.125 +33 maps/dao/lak304d.map 193 194 10 92 94 121 132.64 +33 maps/dao/lak304d.map 193 194 100 129 13 84 133.054 +33 maps/dao/lak304d.map 193 194 100 133 149 22 134.468 +33 maps/dao/lak304d.map 193 194 100 134 5 63 135.539 +33 maps/dao/lak304d.map 193 194 100 134 7 62 133.953 +33 maps/dao/lak304d.map 193 194 100 136 81 168 134.882 +34 maps/dao/lak304d.map 193 194 1 114 46 66 137.669 +34 maps/dao/lak304d.map 193 194 1 77 32 125 136.397 +34 maps/dao/lak304d.map 193 194 1 77 86 149 136.782 +34 maps/dao/lak304d.map 193 194 10 102 33 79 136.569 +34 maps/dao/lak304d.map 193 194 10 117 103 123 137.569 +34 maps/dao/lak304d.map 193 194 10 122 96 80 139.154 +34 maps/dao/lak304d.map 193 194 10 123 133 126 139.983 +34 maps/dao/lak304d.map 193 194 10 123 68 58 138.74 +34 maps/dao/lak304d.map 193 194 10 127 18 67 139.64 +34 maps/dao/lak304d.map 193 194 10 55 61 9 138.48 +35 maps/dao/lak304d.map 193 194 1 114 103 109 142.012 +35 maps/dao/lak304d.map 193 194 10 118 61 53 142.912 +35 maps/dao/lak304d.map 193 194 10 118 80 84 142.811 +35 maps/dao/lak304d.map 193 194 10 128 15 67 143.054 +35 maps/dao/lak304d.map 193 194 10 63 83 167 140.681 +35 maps/dao/lak304d.map 193 194 10 65 109 74 142.024 +35 maps/dao/lak304d.map 193 194 10 81 91 2 140.853 +35 maps/dao/lak304d.map 193 194 10 88 80 154 140.61 +35 maps/dao/lak304d.map 193 194 10 93 115 46 143.882 +35 maps/dao/lak304d.map 193 194 10 93 34 130 140.983 +36 maps/dao/lak304d.map 193 194 1 114 24 67 147.539 +36 maps/dao/lak304d.map 193 194 1 81 112 86 144.368 +36 maps/dao/lak304d.map 193 194 1 92 107 121 147.125 +36 maps/dao/lak304d.map 193 194 10 105 97 89 145.225 +36 maps/dao/lak304d.map 193 194 10 106 130 137 145.326 +36 maps/dao/lak304d.map 193 194 10 112 96 80 145.64 +36 maps/dao/lak304d.map 193 194 10 113 108 123 145.983 +36 maps/dao/lak304d.map 193 194 10 120 112 91 146.154 +36 maps/dao/lak304d.map 193 194 10 122 110 89 144.154 +36 maps/dao/lak304d.map 193 194 10 124 74 89 144.255 +37 maps/dao/lak304d.map 193 194 1 114 107 117 149.326 +37 maps/dao/lak304d.map 193 194 1 92 113 103 148.154 +37 maps/dao/lak304d.map 193 194 10 105 21 70 149.296 +37 maps/dao/lak304d.map 193 194 10 106 24 65 149.711 +37 maps/dao/lak304d.map 193 194 10 121 68 47 150.569 +37 maps/dao/lak304d.map 193 194 10 127 15 57 149.711 +37 maps/dao/lak304d.map 193 194 10 55 15 139 151.368 +37 maps/dao/lak304d.map 193 194 10 73 67 173 148.338 +37 maps/dao/lak304d.map 193 194 10 89 34 116 150.983 +37 maps/dao/lak304d.map 193 194 100 112 106 40 151.64 +38 maps/dao/lak304d.map 193 194 1 115 135 123 155.539 +38 maps/dao/lak304d.map 193 194 1 78 112 71 154.024 +38 maps/dao/lak304d.map 193 194 1 89 24 142 152.125 +38 maps/dao/lak304d.map 193 194 1 92 98 74 152.782 +38 maps/dao/lak304d.map 193 194 10 106 69 55 155.054 +38 maps/dao/lak304d.map 193 194 10 110 141 143 153.154 +38 maps/dao/lak304d.map 193 194 10 115 105 72 155.539 +38 maps/dao/lak304d.map 193 194 10 120 145 123 154.468 +38 maps/dao/lak304d.map 193 194 10 123 123 95 154.255 +38 maps/dao/lak304d.map 193 194 10 124 148 134 155.012 +39 maps/dao/lak304d.map 193 194 1 89 21 138 157.368 +39 maps/dao/lak304d.map 193 194 1 90 100 145 158.61 +39 maps/dao/lak304d.map 193 194 10 104 138 127 159.468 +39 maps/dao/lak304d.map 193 194 10 104 41 54 159.711 +39 maps/dao/lak304d.map 193 194 10 111 13 79 159.711 +39 maps/dao/lak304d.map 193 194 10 124 136 156 158.083 +39 maps/dao/lak304d.map 193 194 10 127 117 71 159.953 +39 maps/dao/lak304d.map 193 194 10 54 108 148 156.853 +39 maps/dao/lak304d.map 193 194 10 54 128 83 158.439 +39 maps/dao/lak304d.map 193 194 10 89 117 75 158.681 +40 maps/dao/lak304d.map 193 194 1 76 72 179 162.51 +40 maps/dao/lak304d.map 193 194 10 112 10 81 161.125 +40 maps/dao/lak304d.map 193 194 10 122 85 45 161.539 +40 maps/dao/lak304d.map 193 194 10 128 22 43 161.368 +40 maps/dao/lak304d.map 193 194 10 54 11 112 162.439 +40 maps/dao/lak304d.map 193 194 10 54 73 178 160.823 +40 maps/dao/lak304d.map 193 194 10 70 9 102 163.711 +40 maps/dao/lak304d.map 193 194 10 72 141 91 163.054 +40 maps/dao/lak304d.map 193 194 10 79 118 149 163.539 +40 maps/dao/lak304d.map 193 194 100 100 100 170 161.539 +41 maps/dao/lak304d.map 193 194 1 76 79 187 167.61 +41 maps/dao/lak304d.map 193 194 1 80 112 137 166.267 +41 maps/dao/lak304d.map 193 194 1 89 105 147 164.024 +41 maps/dao/lak304d.map 193 194 10 106 125 98 167.912 +41 maps/dao/lak304d.map 193 194 10 113 147 156 165.64 +41 maps/dao/lak304d.map 193 194 10 114 142 109 166.196 +41 maps/dao/lak304d.map 193 194 10 118 145 160 164.983 +41 maps/dao/lak304d.map 193 194 10 74 143 93 166.711 +41 maps/dao/lak304d.map 193 194 10 88 110 147 165.953 +41 maps/dao/lak304d.map 193 194 10 89 119 68 165.924 +42 maps/dao/lak304d.map 193 194 1 92 20 106 171.853 +42 maps/dao/lak304d.map 193 194 10 101 145 122 171.539 +42 maps/dao/lak304d.map 193 194 10 108 154 149 170.64 +42 maps/dao/lak304d.map 193 194 10 113 20 43 168.61 +42 maps/dao/lak304d.map 193 194 10 119 140 103 168.125 +42 maps/dao/lak304d.map 193 194 10 124 151 104 169.61 +42 maps/dao/lak304d.map 193 194 10 69 128 137 169.782 +42 maps/dao/lak304d.map 193 194 10 78 9 102 168.539 +42 maps/dao/lak304d.map 193 194 100 148 40 24 170.61 +42 maps/dao/lak304d.map 193 194 100 153 99 48 168.853 +43 maps/dao/lak304d.map 193 194 1 115 82 40 174.853 +43 maps/dao/lak304d.map 193 194 1 116 27 42 172.61 +43 maps/dao/lak304d.map 193 194 1 78 122 149 173.196 +43 maps/dao/lak304d.map 193 194 10 101 3 75 172.539 +43 maps/dao/lak304d.map 193 194 10 102 125 94 173.569 +43 maps/dao/lak304d.map 193 194 10 114 93 46 173.61 +43 maps/dao/lak304d.map 193 194 10 116 149 104 172.095 +43 maps/dao/lak304d.map 193 194 10 128 72 31 175.024 +43 maps/dao/lak304d.map 193 194 10 68 133 139 174.368 +43 maps/dao/lak304d.map 193 194 10 93 12 111 174.953 +44 maps/dao/lak304d.map 193 194 1 90 117 150 177.681 +44 maps/dao/lak304d.map 193 194 10 110 128 76 176.024 +44 maps/dao/lak304d.map 193 194 10 112 137 86 178.882 +44 maps/dao/lak304d.map 193 194 10 112 151 166 178.296 +44 maps/dao/lak304d.map 193 194 10 126 166 119 179.61 +44 maps/dao/lak304d.map 193 194 10 127 85 24 179.782 +44 maps/dao/lak304d.map 193 194 10 60 150 75 178.338 +44 maps/dao/lak304d.map 193 194 10 73 139 65 177.125 +44 maps/dao/lak304d.map 193 194 10 77 145 70 178.024 +44 maps/dao/lak304d.map 193 194 10 92 138 83 179.953 +45 maps/dao/lak304d.map 193 194 1 92 64 184 182.723 +45 maps/dao/lak304d.map 193 194 10 115 163 123 183.167 +45 maps/dao/lak304d.map 193 194 10 118 116 162 180.125 +45 maps/dao/lak304d.map 193 194 10 123 72 25 180.024 +45 maps/dao/lak304d.map 193 194 10 124 76 21 181.953 +45 maps/dao/lak304d.map 193 194 10 126 120 172 180.711 +45 maps/dao/lak304d.map 193 194 10 127 47 29 182.054 +45 maps/dao/lak304d.map 193 194 10 78 151 69 183.681 +45 maps/dao/lak304d.map 193 194 100 163 32 168 183.125 +45 maps/dao/lak304d.map 193 194 100 164 38 98 183.681 +46 maps/dao/lak304d.map 193 194 1 89 145 93 186.853 +46 maps/dao/lak304d.map 193 194 10 109 119 162 184.953 +46 maps/dao/lak304d.map 193 194 10 123 136 72 184.64 +46 maps/dao/lak304d.map 193 194 10 75 147 111 187.953 +46 maps/dao/lak304d.map 193 194 10 80 154 102 187.439 +46 maps/dao/lak304d.map 193 194 100 129 100 180 184.723 +46 maps/dao/lak304d.map 193 194 100 132 101 174 184.238 +46 maps/dao/lak304d.map 193 194 100 164 71 116 187.61 +46 maps/dao/lak304d.map 193 194 100 172 23 155 185.196 +46 maps/dao/lak304d.map 193 194 100 173 102 134 185.995 +47 maps/dao/lak304d.map 193 194 1 115 122 169 189.61 +47 maps/dao/lak304d.map 193 194 1 78 139 140 191.439 +47 maps/dao/lak304d.map 193 194 10 105 118 165 191.196 +47 maps/dao/lak304d.map 193 194 10 119 90 17 190.51 +47 maps/dao/lak304d.map 193 194 10 121 83 15 188.782 +47 maps/dao/lak304d.map 193 194 10 126 80 12 190.125 +47 maps/dao/lak304d.map 193 194 10 73 142 118 191.652 +47 maps/dao/lak304d.map 193 194 10 74 156 59 191.752 +47 maps/dao/lak304d.map 193 194 10 80 145 106 188.782 +47 maps/dao/lak304d.map 193 194 100 164 14 127 190.882 +48 maps/dao/lak304d.map 193 194 10 109 48 30 192.539 +48 maps/dao/lak304d.map 193 194 10 127 105 170 192.368 +48 maps/dao/lak304d.map 193 194 10 127 141 64 193.882 +48 maps/dao/lak304d.map 193 194 10 63 160 61 193.48 +48 maps/dao/lak304d.map 193 194 10 76 144 149 193.267 +48 maps/dao/lak304d.map 193 194 10 76 161 83 194.853 +48 maps/dao/lak304d.map 193 194 10 79 144 112 194.196 +48 maps/dao/lak304d.map 193 194 100 165 26 107 195.296 +48 maps/dao/lak304d.map 193 194 100 166 27 106 195.711 +48 maps/dao/lak304d.map 193 194 100 179 37 94 194.894 +49 maps/dao/lak304d.map 193 194 10 104 93 29 197.095 +49 maps/dao/lak304d.map 193 194 10 118 133 63 196.953 +49 maps/dao/lak304d.map 193 194 10 70 168 62 197.581 +49 maps/dao/lak304d.map 193 194 10 75 152 132 199.853 +49 maps/dao/lak304d.map 193 194 100 114 66 36 196.752 +49 maps/dao/lak304d.map 193 194 100 153 88 3 196.995 +49 maps/dao/lak304d.map 193 194 100 182 25 113 196.167 +49 maps/dao/lak304d.map 193 194 100 44 126 131 199.995 +49 maps/dao/lak304d.map 193 194 101 142 93 4 197.581 +49 maps/dao/lak304d.map 193 194 101 165 12 114 198.368 +50 maps/dao/lak304d.map 193 194 1 112 156 88 201.652 +50 maps/dao/lak304d.map 193 194 1 79 144 127 201.409 +50 maps/dao/lak304d.map 193 194 1 89 131 63 200.51 +50 maps/dao/lak304d.map 193 194 1 92 137 134 202.167 +50 maps/dao/lak304d.map 193 194 10 105 50 23 200.853 +50 maps/dao/lak304d.map 193 194 10 109 127 186 202.953 +50 maps/dao/lak304d.map 193 194 10 121 187 104 203.924 +50 maps/dao/lak304d.map 193 194 10 62 140 47 202.581 +50 maps/dao/lak304d.map 193 194 10 62 143 157 201.338 +50 maps/dao/lak304d.map 193 194 10 62 150 156 203.238 +51 maps/dao/lak304d.map 193 194 1 113 68 12 207.823 +51 maps/dao/lak304d.map 193 194 1 76 151 50 207.338 +51 maps/dao/lak304d.map 193 194 1 82 154 114 205.167 +51 maps/dao/lak304d.map 193 194 10 111 159 73 207.267 +51 maps/dao/lak304d.map 193 194 10 125 191 103 206.681 +51 maps/dao/lak304d.map 193 194 10 61 157 45 207.894 +51 maps/dao/lak304d.map 193 194 10 61 167 113 207.752 +51 maps/dao/lak304d.map 193 194 10 62 149 43 206.167 +51 maps/dao/lak304d.map 193 194 10 71 162 144 204.196 +51 maps/dao/lak304d.map 193 194 10 76 137 44 206.338 +52 maps/dao/lak304d.map 193 194 1 112 118 54 208.095 +52 maps/dao/lak304d.map 193 194 1 76 148 48 208.095 +52 maps/dao/lak304d.map 193 194 1 76 158 136 211.267 +52 maps/dao/lak304d.map 193 194 1 80 148 155 210.409 +52 maps/dao/lak304d.map 193 194 1 92 138 54 209.853 +52 maps/dao/lak304d.map 193 194 10 102 103 160 209.368 +52 maps/dao/lak304d.map 193 194 10 115 126 56 208.681 +52 maps/dao/lak304d.map 193 194 10 122 166 84 210.853 +52 maps/dao/lak304d.map 193 194 10 83 158 139 209.196 +52 maps/dao/lak304d.map 193 194 101 168 31 84 210.167 +53 maps/dao/lak304d.map 193 194 1 76 161 48 215.238 +53 maps/dao/lak304d.map 193 194 1 82 161 93 215.167 +53 maps/dao/lak304d.map 193 194 1 90 138 114 213.409 +53 maps/dao/lak304d.map 193 194 10 102 158 73 215.267 +53 maps/dao/lak304d.map 193 194 10 113 189 126 214.309 +53 maps/dao/lak304d.map 193 194 10 120 154 50 214.51 +53 maps/dao/lak304d.map 193 194 10 124 146 45 214.539 +53 maps/dao/lak304d.map 193 194 10 60 155 162 212.137 +53 maps/dao/lak304d.map 193 194 10 61 123 163 214.137 +53 maps/dao/lak304d.map 193 194 10 68 147 30 215.853 +54 maps/dao/lak304d.map 193 194 1 116 150 57 217.095 +54 maps/dao/lak304d.map 193 194 1 91 147 48 218.581 +54 maps/dao/lak304d.map 193 194 10 63 140 32 217.167 +54 maps/dao/lak304d.map 193 194 10 81 182 85 218.167 +54 maps/dao/lak304d.map 193 194 10 90 135 159 219.338 +54 maps/dao/lak304d.map 193 194 10 92 154 52 216.995 +54 maps/dao/lak304d.map 193 194 10 93 156 117 217.338 +54 maps/dao/lak304d.map 193 194 100 165 59 64 216.853 +54 maps/dao/lak304d.map 193 194 100 44 129 55 219.338 +54 maps/dao/lak304d.map 193 194 100 46 161 68 217.409 +55 maps/dao/lak304d.map 193 194 1 76 183 65 221.995 +55 maps/dao/lak304d.map 193 194 1 91 167 89 222.066 +55 maps/dao/lak304d.map 193 194 10 106 166 79 220.095 +55 maps/dao/lak304d.map 193 194 10 60 153 174 223.309 +55 maps/dao/lak304d.map 193 194 10 66 179 101 221.823 +55 maps/dao/lak304d.map 193 194 10 71 112 166 222.238 +55 maps/dao/lak304d.map 193 194 10 73 163 157 220.439 +55 maps/dao/lak304d.map 193 194 10 82 159 39 220.409 +55 maps/dao/lak304d.map 193 194 10 88 155 158 222.238 +55 maps/dao/lak304d.map 193 194 100 42 145 117 223.924 +56 maps/dao/lak304d.map 193 194 1 78 188 67 226.995 +56 maps/dao/lak304d.map 193 194 1 91 163 121 224.894 +56 maps/dao/lak304d.map 193 194 10 108 159 51 226.409 +56 maps/dao/lak304d.map 193 194 10 123 132 43 224.267 +56 maps/dao/lak304d.map 193 194 10 125 184 85 226.853 +56 maps/dao/lak304d.map 193 194 10 61 150 24 225.995 +56 maps/dao/lak304d.map 193 194 10 70 157 24 225.167 +56 maps/dao/lak304d.map 193 194 10 72 122 177 224.238 +56 maps/dao/lak304d.map 193 194 10 76 111 163 225.238 +56 maps/dao/lak304d.map 193 194 10 82 127 171 226.409 +57 maps/dao/lak304d.map 193 194 10 110 118 190 229.238 +57 maps/dao/lak304d.map 193 194 10 111 145 38 229.439 +57 maps/dao/lak304d.map 193 194 10 112 149 40 228.095 +57 maps/dao/lak304d.map 193 194 10 117 170 45 229.723 +57 maps/dao/lak304d.map 193 194 10 61 131 177 228.38 +57 maps/dao/lak304d.map 193 194 10 63 185 130 231.966 +57 maps/dao/lak304d.map 193 194 10 78 125 180 230.823 +57 maps/dao/lak304d.map 193 194 100 165 61 51 230.681 +57 maps/dao/lak304d.map 193 194 100 178 20 91 229.794 +57 maps/dao/lak304d.map 193 194 100 181 25 67 228.865 +58 maps/dao/lak304d.map 193 194 10 101 173 65 234.581 +58 maps/dao/lak304d.map 193 194 10 65 187 125 234.38 +58 maps/dao/lak304d.map 193 194 10 82 169 34 232.48 +58 maps/dao/lak304d.map 193 194 10 89 190 77 234.167 +58 maps/dao/lak304d.map 193 194 100 174 16 69 232.38 +58 maps/dao/lak304d.map 193 194 100 42 162 106 232.652 +58 maps/dao/lak304d.map 193 194 100 43 174 85 232.894 +58 maps/dao/lak304d.map 193 194 100 50 173 55 233.137 +58 maps/dao/lak304d.map 193 194 100 51 179 69 233.752 +58 maps/dao/lak304d.map 193 194 101 42 146 160 234.238 +59 maps/dao/lak304d.map 193 194 1 112 178 56 238.966 +59 maps/dao/lak304d.map 193 194 10 106 146 35 237.853 +59 maps/dao/lak304d.map 193 194 10 118 140 27 236.681 +59 maps/dao/lak304d.map 193 194 10 73 101 177 238.622 +59 maps/dao/lak304d.map 193 194 10 82 107 168 237.309 +59 maps/dao/lak304d.map 193 194 10 93 155 169 236.48 +59 maps/dao/lak304d.map 193 194 100 37 178 82 238.137 +59 maps/dao/lak304d.map 193 194 100 51 150 165 236.995 +59 maps/dao/lak304d.map 193 194 100 51 174 110 239.51 +59 maps/dao/lak304d.map 193 194 101 161 28 47 239.894 +60 maps/dao/lak304d.map 193 194 1 82 184 125 243.037 +60 maps/dao/lak304d.map 193 194 1 89 180 103 240.48 +60 maps/dao/lak304d.map 193 194 10 78 99 166 240.48 +60 maps/dao/lak304d.map 193 194 100 182 13 65 240.35 +60 maps/dao/lak304d.map 193 194 100 38 127 163 240.794 +60 maps/dao/lak304d.map 193 194 101 165 11 54 241.794 +60 maps/dao/lak304d.map 193 194 101 39 166 126 242.208 +60 maps/dao/lak304d.map 193 194 101 48 146 33 241.095 +60 maps/dao/lak304d.map 193 194 101 52 135 36 241.823 +60 maps/dao/lak304d.map 193 194 102 165 23 49 243.309 +61 maps/dao/lak304d.map 193 194 1 113 171 40 245.794 +61 maps/dao/lak304d.map 193 194 1 114 174 40 246.622 +61 maps/dao/lak304d.map 193 194 10 113 160 27 244.652 +61 maps/dao/lak304d.map 193 194 100 178 69 44 246.38 +61 maps/dao/lak304d.map 193 194 100 48 174 128 245.723 +61 maps/dao/lak304d.map 193 194 101 179 75 48 244.279 +61 maps/dao/lak304d.map 193 194 101 41 142 32 245.823 +61 maps/dao/lak304d.map 193 194 101 45 156 167 244.137 +61 maps/dao/lak304d.map 193 194 101 46 148 28 247.752 +61 maps/dao/lak304d.map 193 194 101 50 184 60 244.723 +62 maps/dao/lak304d.map 193 194 1 90 108 174 250.522 +62 maps/dao/lak304d.map 193 194 1 90 111 176 248.35 +62 maps/dao/lak304d.map 193 194 10 111 154 21 250.167 +62 maps/dao/lak304d.map 193 194 100 172 43 42 248.38 +62 maps/dao/lak304d.map 193 194 100 42 112 161 251.551 +62 maps/dao/lak304d.map 193 194 100 42 174 134 251.279 +62 maps/dao/lak304d.map 193 194 100 44 166 156 249.581 +62 maps/dao/lak304d.map 193 194 100 47 129 172 248.894 +62 maps/dao/lak304d.map 193 194 101 167 26 40 249.38 +62 maps/dao/lak304d.map 193 194 101 174 79 41 250.865 +63 maps/dao/lak304d.map 193 194 1 92 186 128 252.622 +63 maps/dao/lak304d.map 193 194 10 81 109 183 252.279 +63 maps/dao/lak304d.map 193 194 100 169 24 37 255.037 +63 maps/dao/lak304d.map 193 194 101 174 89 53 252.38 +63 maps/dao/lak304d.map 193 194 101 179 15 86 252.279 +63 maps/dao/lak304d.map 193 194 101 48 185 103 254.823 +63 maps/dao/lak304d.map 193 194 102 181 22 44 253.593 +63 maps/dao/lak304d.map 193 194 102 38 143 25 254.652 +63 maps/dao/lak304d.map 193 194 102 47 181 102 252.652 +63 maps/dao/lak304d.map 193 194 103 165 83 34 253.794 +64 maps/dao/lak304d.map 193 194 10 75 115 192 258.936 +64 maps/dao/lak304d.map 193 194 10 89 100 181 258.35 +64 maps/dao/lak304d.map 193 194 100 176 30 33 259.451 +64 maps/dao/lak304d.map 193 194 101 178 29 35 257.693 +64 maps/dao/lak304d.map 193 194 101 182 30 36 258.522 +64 maps/dao/lak304d.map 193 194 102 164 24 32 256.551 +64 maps/dao/lak304d.map 193 194 102 165 55 33 257.451 +64 maps/dao/lak304d.map 193 194 103 179 33 30 259.451 +64 maps/dao/lak304d.map 193 194 103 182 89 46 258.35 +64 maps/dao/lak304d.map 193 194 103 190 48 44 259.35 +65 maps/dao/lak304d.map 193 194 100 42 135 181 261.279 +65 maps/dao/lak304d.map 193 194 100 43 127 186 262.551 +65 maps/dao/lak304d.map 193 194 100 50 188 116 263.581 +65 maps/dao/lak304d.map 193 194 102 190 43 42 260.279 +65 maps/dao/lak304d.map 193 194 102 48 188 127 262.966 +65 maps/dao/lak304d.map 193 194 104 179 81 32 260.35 +65 maps/dao/lak304d.map 193 194 104 39 110 158 260.622 +65 maps/dao/lak304d.map 193 194 104 45 155 22 260.066 +65 maps/dao/lak304d.map 193 194 105 162 46 25 263.723 +65 maps/dao/lak304d.map 193 194 105 41 185 103 261.723 +66 maps/dao/lak304d.map 193 194 100 164 85 25 266.208 +66 maps/dao/lak304d.map 193 194 100 42 103 172 265.108 +66 maps/dao/lak304d.map 193 194 102 165 41 21 266.966 +66 maps/dao/lak304d.map 193 194 102 181 97 46 265.764 +66 maps/dao/lak304d.map 193 194 102 46 136 183 264.037 +66 maps/dao/lak304d.map 193 194 103 162 105 40 266.794 +66 maps/dao/lak304d.map 193 194 103 39 106 175 267.593 +66 maps/dao/lak304d.map 193 194 103 40 108 176 265.593 +66 maps/dao/lak304d.map 193 194 103 45 103 170 266.037 +66 maps/dao/lak304d.map 193 194 104 175 38 24 264.865 +67 maps/dao/lak304d.map 193 194 1 82 118 188 270.421 +67 maps/dao/lak304d.map 193 194 100 162 91 21 271.865 +67 maps/dao/lak304d.map 193 194 100 166 43 20 271.208 +67 maps/dao/lak304d.map 193 194 100 173 88 28 268.764 +67 maps/dao/lak304d.map 193 194 101 163 84 20 269.38 +67 maps/dao/lak304d.map 193 194 101 175 44 32 269.037 +67 maps/dao/lak304d.map 193 194 102 166 76 20 269.622 +67 maps/dao/lak304d.map 193 194 103 164 105 53 269.309 +67 maps/dao/lak304d.map 193 194 103 179 88 28 268.25 +67 maps/dao/lak304d.map 193 194 103 190 55 35 271.25 +68 maps/dao/lak304d.map 193 194 100 176 87 22 275.007 +68 maps/dao/lak304d.map 193 194 101 167 110 53 273.794 +68 maps/dao/lak304d.map 193 194 102 176 106 42 273.764 +68 maps/dao/lak304d.map 193 194 102 178 93 32 273.593 +68 maps/dao/lak304d.map 193 194 105 175 72 20 272.007 +68 maps/dao/lak304d.map 193 194 106 168 115 48 272.966 +68 maps/dao/lak304d.map 193 194 107 177 80 13 275.936 +68 maps/dao/lak304d.map 193 194 109 176 82 10 275.936 +68 maps/dao/lak304d.map 193 194 109 181 88 30 274.007 +68 maps/dao/lak304d.map 193 194 109 53 102 173 274.865 +69 maps/dao/lak304d.map 193 194 102 182 108 47 277.35 +69 maps/dao/lak304d.map 193 194 103 164 71 13 279.936 +69 maps/dao/lak304d.map 193 194 103 168 113 42 276.451 +69 maps/dao/lak304d.map 193 194 103 184 90 22 279.492 +69 maps/dao/lak304d.map 193 194 104 166 113 56 279.551 +69 maps/dao/lak304d.map 193 194 104 167 105 62 279.38 +69 maps/dao/lak304d.map 193 194 104 174 116 52 279.279 +69 maps/dao/lak304d.map 193 194 104 181 109 54 278.936 +69 maps/dao/lak304d.map 193 194 105 172 115 45 276.865 +69 maps/dao/lak304d.map 193 194 105 174 116 47 277.865 +70 maps/dao/lak304d.map 193 194 100 166 116 42 281.622 +70 maps/dao/lak304d.map 193 194 100 178 112 46 280.936 +70 maps/dao/lak304d.map 193 194 102 168 87 9 282.693 +70 maps/dao/lak304d.map 193 194 102 41 103 190 281.421 +70 maps/dao/lak304d.map 193 194 103 186 89 20 283.078 +70 maps/dao/lak304d.map 193 194 103 190 75 25 280.421 +70 maps/dao/lak304d.map 193 194 103 46 113 181 282.764 +70 maps/dao/lak304d.map 193 194 105 188 106 48 280.522 +70 maps/dao/lak304d.map 193 194 106 177 65 14 281.321 +70 maps/dao/lak304d.map 193 194 107 181 43 17 281.179 +71 maps/dao/lak304d.map 193 194 100 181 118 48 287.35 +71 maps/dao/lak304d.map 193 194 101 175 85 7 287.764 +71 maps/dao/lak304d.map 193 194 102 173 121 46 285.865 +71 maps/dao/lak304d.map 193 194 103 163 92 4 286.693 +71 maps/dao/lak304d.map 193 194 103 170 88 4 287.936 +71 maps/dao/lak304d.map 193 194 103 179 86 9 285.836 +71 maps/dao/lak304d.map 193 194 103 183 116 52 286.35 +71 maps/dao/lak304d.map 193 194 103 188 108 53 284.936 +71 maps/dao/lak304d.map 193 194 105 173 61 12 285.492 +71 maps/dao/lak304d.map 193 194 109 181 87 17 284.836 +72 maps/dao/lak304d.map 193 194 101 182 118 53 288.593 +72 maps/dao/lak304d.map 193 194 103 171 89 4 288.764 +72 maps/dao/lak304d.map 193 194 103 178 123 44 289.764 +72 maps/dao/lak304d.map 193 194 104 188 116 48 290.108 +72 maps/dao/lak304d.map 193 194 105 189 113 41 291.421 +72 maps/dao/lak304d.map 193 194 112 41 112 183 290.836 +72 maps/dao/lak304d.map 193 194 114 183 89 17 291.492 +72 maps/dao/lak304d.map 193 194 114 53 111 184 291.764 +72 maps/dao/lak304d.map 193 194 115 46 111 183 290.764 +72 maps/dao/lak304d.map 193 194 116 172 60 24 289.321 +73 maps/dao/lak304d.map 193 194 100 171 92 4 293.007 +73 maps/dao/lak304d.map 193 194 102 182 60 11 294.806 +73 maps/dao/lak304d.map 193 194 102 190 90 16 292.492 +73 maps/dao/lak304d.map 193 194 105 61 109 188 295.593 +73 maps/dao/lak304d.map 193 194 107 188 117 53 293.593 +73 maps/dao/lak304d.map 193 194 109 180 118 43 292.593 +73 maps/dao/lak304d.map 193 194 116 182 114 47 294.764 +73 maps/dao/lak304d.map 193 194 118 187 93 29 292.078 +73 maps/dao/lak304d.map 193 194 119 47 109 188 295.593 +73 maps/dao/lak304d.map 193 194 128 175 60 27 292.007 +74 maps/dao/lak304d.map 193 194 101 178 55 13 297.149 +74 maps/dao/lak304d.map 193 194 101 182 58 9 298.049 +74 maps/dao/lak304d.map 193 194 103 185 60 9 298.22 +74 maps/dao/lak304d.map 193 194 107 184 61 11 296.22 +74 maps/dao/lak304d.map 193 194 109 163 62 28 296.836 +74 maps/dao/lak304d.map 193 194 110 186 72 10 298.635 +74 maps/dao/lak304d.map 193 194 110 192 118 48 299.179 +74 maps/dao/lak304d.map 193 194 112 49 114 192 296.179 +74 maps/dao/lak304d.map 193 194 114 161 66 33 298.25 +74 maps/dao/lak304d.map 193 194 114 182 92 12 298.149 +75 maps/dao/lak304d.map 193 194 100 176 78 2 300.593 +75 maps/dao/lak304d.map 193 194 103 186 55 13 302.563 +75 maps/dao/lak304d.map 193 194 106 63 114 179 301.764 +75 maps/dao/lak304d.map 193 194 109 164 64 31 301.078 +75 maps/dao/lak304d.map 193 194 111 192 116 42 300.078 +75 maps/dao/lak304d.map 193 194 113 182 88 7 301.078 +75 maps/dao/lak304d.map 193 194 116 182 87 9 301.078 +75 maps/dao/lak304d.map 193 194 125 176 64 33 300.25 +75 maps/dao/lak304d.map 193 194 173 39 67 38 303.635 +75 maps/dao/lak304d.map 193 194 185 120 75 2 300.108 +76 maps/dao/lak304d.map 193 194 109 181 79 1 304.836 +76 maps/dao/lak304d.map 193 194 136 174 63 31 305.907 +76 maps/dao/lak304d.map 193 194 61 9 110 190 304.877 +76 maps/dao/lak304d.map 193 194 63 27 135 184 305.735 +76 maps/dao/lak304d.map 193 194 64 32 184 131 305.735 +76 maps/dao/lak304d.map 193 194 67 38 162 158 305.936 +77 maps/dao/lak304d.map 193 194 106 186 58 21 308.22 +77 maps/dao/lak304d.map 193 194 108 181 71 2 311.421 +77 maps/dao/lak304d.map 193 194 108 185 59 20 308.049 +77 maps/dao/lak304d.map 193 194 118 188 87 5 310.492 +77 maps/dao/lak304d.map 193 194 135 175 67 35 310.149 +77 maps/dao/lak304d.map 193 194 186 126 65 34 310.563 +77 maps/dao/lak304d.map 193 194 55 12 116 182 310.806 diff --git a/node_modules/pathfinding/benchmark/scen/losttemple.map.scen b/node_modules/pathfinding/benchmark/scen/losttemple.map.scen new file mode 100644 index 0000000..bd836c3 --- /dev/null +++ b/node_modules/pathfinding/benchmark/scen/losttemple.map.scen @@ -0,0 +1,1239 @@ +version 1.0 +66 maps/wc3maps/losttemple.map 512 512 242 400 121 216 265.58 +60 maps/wc3maps/losttemple.map 512 512 360 249 145 312 241.10 +34 maps/wc3maps/losttemple.map 512 512 108 204 222 264 138.85 +77 maps/wc3maps/losttemple.map 512 512 358 110 137 303 309.97 +70 maps/wc3maps/losttemple.map 512 512 402 269 188 370 282.06 +54 maps/wc3maps/losttemple.map 512 512 279 218 279 422 218.67 +45 maps/wc3maps/losttemple.map 512 512 327 241 287 77 183.50 +45 maps/wc3maps/losttemple.map 512 512 210 208 175 366 183.04 +17 maps/wc3maps/losttemple.map 512 512 74 264 90 328 70.63 +61 maps/wc3maps/losttemple.map 512 512 414 323 234 408 244.66 +53 maps/wc3maps/losttemple.map 512 512 396 251 228 142 213.15 +28 maps/wc3maps/losttemple.map 512 512 152 317 196 231 112.81 +97 maps/wc3maps/losttemple.map 512 512 111 377 400 180 388.42 +57 maps/wc3maps/losttemple.map 512 512 208 237 401 146 230.69 +31 maps/wc3maps/losttemple.map 512 512 202 282 112 225 127.81 +44 maps/wc3maps/losttemple.map 512 512 92 257 214 366 176.52 +21 maps/wc3maps/losttemple.map 512 512 190 175 265 149 85.77 +96 maps/wc3maps/losttemple.map 512 512 424 103 178 380 385.93 +58 maps/wc3maps/losttemple.map 512 512 203 125 403 152 235.55 +71 maps/wc3maps/losttemple.map 512 512 111 243 301 391 286.01 +21 maps/wc3maps/losttemple.map 512 512 186 289 215 364 87.01 +88 maps/wc3maps/losttemple.map 512 512 281 413 231 81 352.71 +90 maps/wc3maps/losttemple.map 512 512 392 119 83 215 361.79 +20 maps/wc3maps/losttemple.map 512 512 238 431 304 391 82.57 +27 maps/wc3maps/losttemple.map 512 512 402 201 335 280 109.68 +30 maps/wc3maps/losttemple.map 512 512 405 291 303 239 123.54 +104 maps/wc3maps/losttemple.map 512 512 144 336 438 92 417.33 +54 maps/wc3maps/losttemple.map 512 512 398 290 302 416 217.14 +13 maps/wc3maps/losttemple.map 512 512 140 361 152 312 53.97 +70 maps/wc3maps/losttemple.map 512 512 378 145 197 321 280.26 +72 maps/wc3maps/losttemple.map 512 512 261 349 343 98 288.28 +14 maps/wc3maps/losttemple.map 512 512 179 247 158 297 58.70 +33 maps/wc3maps/losttemple.map 512 512 158 331 58 252 132.72 +33 maps/wc3maps/losttemple.map 512 512 301 251 387 179 132.23 +57 maps/wc3maps/losttemple.map 512 512 427 196 439 128 230.74 +46 maps/wc3maps/losttemple.map 512 512 87 304 269 311 186.90 +44 maps/wc3maps/losttemple.map 512 512 142 354 176 189 179.08 +70 maps/wc3maps/losttemple.map 512 512 205 161 263 416 281.95 +26 maps/wc3maps/losttemple.map 512 512 350 290 273 297 107.78 +91 maps/wc3maps/losttemple.map 512 512 419 211 121 372 364.69 +4 maps/wc3maps/losttemple.map 512 512 390 443 377 432 17.56 +62 maps/wc3maps/losttemple.map 512 512 210 380 388 278 248.53 +93 maps/wc3maps/losttemple.map 512 512 313 176 100 428 372.45 +3 maps/wc3maps/losttemple.map 512 512 76 430 77 415 15.41 +54 maps/wc3maps/losttemple.map 512 512 135 258 266 290 219.81 +34 maps/wc3maps/losttemple.map 512 512 304 301 414 255 139.58 +14 maps/wc3maps/losttemple.map 512 512 287 399 288 351 57.49 +15 maps/wc3maps/losttemple.map 512 512 142 126 89 145 63.36 +35 maps/wc3maps/losttemple.map 512 512 189 109 210 202 141.36 +36 maps/wc3maps/losttemple.map 512 512 294 429 232 309 145.68 +46 maps/wc3maps/losttemple.map 512 512 111 216 253 324 187.32 +37 maps/wc3maps/losttemple.map 512 512 280 293 230 163 150.71 +65 maps/wc3maps/losttemple.map 512 512 404 253 200 117 260.33 +86 maps/wc3maps/losttemple.map 512 512 393 282 67 229 347.95 +58 maps/wc3maps/losttemple.map 512 512 75 396 122 216 232.92 +35 maps/wc3maps/losttemple.map 512 512 326 154 200 188 140.08 +46 maps/wc3maps/losttemple.map 512 512 327 353 156 316 186.33 +95 maps/wc3maps/losttemple.map 512 512 73 425 225 108 382.45 +30 maps/wc3maps/losttemple.map 512 512 218 411 146 350 122.50 +68 maps/wc3maps/losttemple.map 512 512 339 71 136 238 272.76 +34 maps/wc3maps/losttemple.map 512 512 175 140 176 248 137.95 +58 maps/wc3maps/losttemple.map 512 512 424 92 259 211 235.38 +100 maps/wc3maps/losttemple.map 512 512 76 387 290 106 403.03 +52 maps/wc3maps/losttemple.map 512 512 139 338 298 235 208.11 +48 maps/wc3maps/losttemple.map 512 512 269 291 115 271 193.50 +69 maps/wc3maps/losttemple.map 512 512 273 179 206 421 276.82 +43 maps/wc3maps/losttemple.map 512 512 221 249 320 122 175.87 +19 maps/wc3maps/losttemple.map 512 512 193 304 231 269 78.07 +67 maps/wc3maps/losttemple.map 512 512 104 308 367 298 271.28 +56 maps/wc3maps/losttemple.map 512 512 349 195 278 389 225.75 +59 maps/wc3maps/losttemple.map 512 512 353 134 241 305 238.14 +9 maps/wc3maps/losttemple.map 512 512 277 375 294 349 39.49 +35 maps/wc3maps/losttemple.map 512 512 312 335 194 387 141.30 +41 maps/wc3maps/losttemple.map 512 512 317 340 338 182 166.70 +55 maps/wc3maps/losttemple.map 512 512 228 272 86 402 223.91 +3 maps/wc3maps/losttemple.map 512 512 435 307 428 317 12.90 +31 maps/wc3maps/losttemple.map 512 512 255 266 361 218 125.88 +49 maps/wc3maps/losttemple.map 512 512 81 203 192 349 196.66 +76 maps/wc3maps/losttemple.map 512 512 366 77 266 335 307.42 +20 maps/wc3maps/losttemple.map 512 512 243 127 275 194 80.25 +36 maps/wc3maps/losttemple.map 512 512 303 395 189 331 144.02 +43 maps/wc3maps/losttemple.map 512 512 144 216 76 344 172.57 +119 maps/wc3maps/losttemple.map 512 512 411 149 70 437 476.70 +7 maps/wc3maps/losttemple.map 512 512 334 256 349 280 30.21 +38 maps/wc3maps/losttemple.map 512 512 146 389 77 298 152.33 +65 maps/wc3maps/losttemple.map 512 512 437 246 234 121 261.22 +37 maps/wc3maps/losttemple.map 512 512 269 223 162 305 150.92 +6 maps/wc3maps/losttemple.map 512 512 71 299 87 319 26.63 +41 maps/wc3maps/losttemple.map 512 512 135 397 82 265 166.10 +48 maps/wc3maps/losttemple.map 512 512 183 389 141 212 194.40 +51 maps/wc3maps/losttemple.map 512 512 402 315 226 239 207.48 +36 maps/wc3maps/losttemple.map 512 512 358 111 371 223 147.37 +66 maps/wc3maps/losttemple.map 512 512 376 155 136 221 267.34 +11 maps/wc3maps/losttemple.map 512 512 98 317 136 299 46.04 +69 maps/wc3maps/losttemple.map 512 512 124 357 355 243 278.22 +45 maps/wc3maps/losttemple.map 512 512 207 191 68 274 180.99 +36 maps/wc3maps/losttemple.map 512 512 398 143 386 249 145.52 +31 maps/wc3maps/losttemple.map 512 512 341 190 227 219 127.67 +57 maps/wc3maps/losttemple.map 512 512 245 309 346 131 230.04 +18 maps/wc3maps/losttemple.map 512 512 244 319 184 297 73.25 +39 maps/wc3maps/losttemple.map 512 512 429 300 320 370 158.50 +9 maps/wc3maps/losttemple.map 512 512 352 420 383 439 38.87 +40 maps/wc3maps/losttemple.map 512 512 272 116 385 174 160.20 +60 maps/wc3maps/losttemple.map 512 512 295 418 321 204 241.34 +99 maps/wc3maps/losttemple.map 512 512 174 445 285 102 397.18 +59 maps/wc3maps/losttemple.map 512 512 243 411 420 309 237.11 +35 maps/wc3maps/losttemple.map 512 512 344 128 221 170 140.40 +47 maps/wc3maps/losttemple.map 512 512 270 121 408 136 188.92 +65 maps/wc3maps/losttemple.map 512 512 92 311 208 125 260.41 +13 maps/wc3maps/losttemple.map 512 512 232 104 252 147 53.04 +43 maps/wc3maps/losttemple.map 512 512 404 118 286 101 175.51 +89 maps/wc3maps/losttemple.map 512 512 197 432 240 93 356.81 +83 maps/wc3maps/losttemple.map 512 512 130 306 338 80 333.83 +47 maps/wc3maps/losttemple.map 512 512 434 215 261 257 190.40 +45 maps/wc3maps/losttemple.map 512 512 106 389 258 363 182.57 +102 maps/wc3maps/losttemple.map 512 512 123 387 406 130 408.20 +37 maps/wc3maps/losttemple.map 512 512 342 93 200 117 151.94 +70 maps/wc3maps/losttemple.map 512 512 179 246 426 159 283.04 +18 maps/wc3maps/losttemple.map 512 512 387 389 399 436 72.21 +61 maps/wc3maps/losttemple.map 512 512 334 353 252 146 246.62 +92 maps/wc3maps/losttemple.map 512 512 421 162 122 314 370.16 +72 maps/wc3maps/losttemple.map 512 512 83 439 88 197 290.46 +24 maps/wc3maps/losttemple.map 512 512 408 218 350 180 97.94 +90 maps/wc3maps/losttemple.map 512 512 86 333 426 318 362.78 +20 maps/wc3maps/losttemple.map 512 512 431 235 426 164 82.18 +55 maps/wc3maps/losttemple.map 512 512 210 160 306 334 221.38 +55 maps/wc3maps/losttemple.map 512 512 275 186 131 328 220.78 +53 maps/wc3maps/losttemple.map 512 512 309 271 187 392 215.15 +51 maps/wc3maps/losttemple.map 512 512 321 245 424 83 205.84 +52 maps/wc3maps/losttemple.map 512 512 338 131 177 252 211.12 +49 maps/wc3maps/losttemple.map 512 512 263 86 417 154 199.54 +19 maps/wc3maps/losttemple.map 512 512 265 291 287 356 77.18 +25 maps/wc3maps/losttemple.map 512 512 281 359 215 435 103.92 +75 maps/wc3maps/losttemple.map 512 512 280 366 336 91 301.51 +53 maps/wc3maps/losttemple.map 512 512 307 194 206 338 215.15 +39 maps/wc3maps/losttemple.map 512 512 273 322 278 187 159.80 +60 maps/wc3maps/losttemple.map 512 512 89 293 172 140 242.84 +46 maps/wc3maps/losttemple.map 512 512 193 328 355 270 186.02 +43 maps/wc3maps/losttemple.map 512 512 316 239 291 118 175.11 +84 maps/wc3maps/losttemple.map 512 512 224 86 337 374 338.32 +38 maps/wc3maps/losttemple.map 512 512 99 377 88 335 152.40 +43 maps/wc3maps/losttemple.map 512 512 176 430 106 412 173.68 +31 maps/wc3maps/losttemple.map 512 512 292 213 366 298 124.44 +57 maps/wc3maps/losttemple.map 512 512 278 386 177 213 228.49 +13 maps/wc3maps/losttemple.map 512 512 268 265 257 310 53.07 +42 maps/wc3maps/losttemple.map 512 512 277 364 135 300 168.51 +9 maps/wc3maps/losttemple.map 512 512 319 109 352 111 39.49 +52 maps/wc3maps/losttemple.map 512 512 337 128 336 327 210.18 +37 maps/wc3maps/losttemple.map 512 512 348 250 236 165 148.38 +52 maps/wc3maps/losttemple.map 512 512 446 110 266 175 211.07 +44 maps/wc3maps/losttemple.map 512 512 156 284 321 318 179.91 +26 maps/wc3maps/losttemple.map 512 512 321 330 229 312 104.14 +21 maps/wc3maps/losttemple.map 512 512 207 296 287 307 85.38 +24 maps/wc3maps/losttemple.map 512 512 151 171 167 83 97.94 +56 maps/wc3maps/losttemple.map 512 512 275 126 98 202 225.88 +3 maps/wc3maps/losttemple.map 512 512 449 217 452 204 14.24 +50 maps/wc3maps/losttemple.map 512 512 405 242 206 247 201.07 +50 maps/wc3maps/losttemple.map 512 512 212 155 355 290 201.26 +64 maps/wc3maps/losttemple.map 512 512 137 253 199 132 256.38 +22 maps/wc3maps/losttemple.map 512 512 87 321 168 336 88.87 +87 maps/wc3maps/losttemple.map 512 512 289 98 280 409 351.10 +67 maps/wc3maps/losttemple.map 512 512 364 273 122 328 268.92 +36 maps/wc3maps/losttemple.map 512 512 262 330 256 187 145.49 +79 maps/wc3maps/losttemple.map 512 512 440 196 152 272 319.48 +59 maps/wc3maps/losttemple.map 512 512 173 151 112 322 237.38 +100 maps/wc3maps/losttemple.map 512 512 335 90 121 387 400.29 +50 maps/wc3maps/losttemple.map 512 512 117 234 190 406 203.99 +28 maps/wc3maps/losttemple.map 512 512 225 334 142 377 114.57 +50 maps/wc3maps/losttemple.map 512 512 128 229 267 94 201.95 +68 maps/wc3maps/losttemple.map 512 512 348 67 141 226 272.86 +50 maps/wc3maps/losttemple.map 512 512 92 222 283 242 200.94 +58 maps/wc3maps/losttemple.map 512 512 85 301 239 398 232.52 +59 maps/wc3maps/losttemple.map 512 512 261 384 76 330 236.88 +73 maps/wc3maps/losttemple.map 512 512 393 248 115 212 293.74 +103 maps/wc3maps/losttemple.map 512 512 63 433 242 94 413.73 +43 maps/wc3maps/losttemple.map 512 512 118 392 163 454 175.61 +53 maps/wc3maps/losttemple.map 512 512 285 350 182 198 212.46 +70 maps/wc3maps/losttemple.map 512 512 378 280 121 331 283.44 +29 maps/wc3maps/losttemple.map 512 512 427 315 353 231 116.99 +22 maps/wc3maps/losttemple.map 512 512 359 340 341 421 88.46 +88 maps/wc3maps/losttemple.map 512 512 272 113 281 436 355.30 +20 maps/wc3maps/losttemple.map 512 512 196 331 198 413 82.83 +30 maps/wc3maps/losttemple.map 512 512 363 167 333 278 123.43 +19 maps/wc3maps/losttemple.map 512 512 262 145 280 98 79.43 +57 maps/wc3maps/losttemple.map 512 512 321 239 198 409 230.46 +86 maps/wc3maps/losttemple.map 512 512 405 277 81 243 345.05 +63 maps/wc3maps/losttemple.map 512 512 399 155 163 202 255.47 +75 maps/wc3maps/losttemple.map 512 512 88 205 346 306 301.49 +74 maps/wc3maps/losttemple.map 512 512 347 259 81 339 299.14 +47 maps/wc3maps/losttemple.map 512 512 110 267 109 424 191.58 +55 maps/wc3maps/losttemple.map 512 512 231 153 132 331 221.94 +30 maps/wc3maps/losttemple.map 512 512 241 351 207 244 121.08 +50 maps/wc3maps/losttemple.map 512 512 412 140 247 212 201.85 +70 maps/wc3maps/losttemple.map 512 512 326 373 347 105 282.50 +54 maps/wc3maps/losttemple.map 512 512 411 150 227 225 217.99 +51 maps/wc3maps/losttemple.map 512 512 403 316 393 163 206.28 +36 maps/wc3maps/losttemple.map 512 512 438 141 313 168 146.12 +56 maps/wc3maps/losttemple.map 512 512 281 382 159 214 225.56 +77 maps/wc3maps/losttemple.map 512 512 164 265 441 186 309.72 +65 maps/wc3maps/losttemple.map 512 512 403 293 436 92 263.89 +83 maps/wc3maps/losttemple.map 512 512 74 447 239 187 334.79 +76 maps/wc3maps/losttemple.map 512 512 64 436 255 229 306.03 +81 maps/wc3maps/losttemple.map 512 512 196 376 293 109 324.17 +43 maps/wc3maps/losttemple.map 512 512 137 268 145 379 174.44 +8 maps/wc3maps/losttemple.map 512 512 255 104 283 121 35.04 +65 maps/wc3maps/losttemple.map 512 512 329 140 201 332 260.84 +20 maps/wc3maps/losttemple.map 512 512 237 350 317 352 80.83 +69 maps/wc3maps/losttemple.map 512 512 347 282 100 345 278.41 +63 maps/wc3maps/losttemple.map 512 512 419 319 193 250 254.58 +14 maps/wc3maps/losttemple.map 512 512 53 347 71 295 59.46 +42 maps/wc3maps/losttemple.map 512 512 273 183 153 289 168.59 +27 maps/wc3maps/losttemple.map 512 512 164 326 105 411 109.44 +49 maps/wc3maps/losttemple.map 512 512 415 104 286 93 197.38 +110 maps/wc3maps/losttemple.map 512 512 89 422 430 182 441.00 +20 maps/wc3maps/losttemple.map 512 512 133 354 73 395 82.84 +67 maps/wc3maps/losttemple.map 512 512 210 338 190 112 268.95 +24 maps/wc3maps/losttemple.map 512 512 354 95 376 159 98.28 +73 maps/wc3maps/losttemple.map 512 512 176 328 440 253 295.07 +22 maps/wc3maps/losttemple.map 512 512 181 200 166 283 89.21 +77 maps/wc3maps/losttemple.map 512 512 128 383 367 214 309.59 +37 maps/wc3maps/losttemple.map 512 512 149 348 271 278 150.99 +36 maps/wc3maps/losttemple.map 512 512 139 358 181 237 144.25 +35 maps/wc3maps/losttemple.map 512 512 171 208 89 283 143.23 +85 maps/wc3maps/losttemple.map 512 512 145 353 292 70 343.89 +39 maps/wc3maps/losttemple.map 512 512 293 274 345 156 156.27 +61 maps/wc3maps/losttemple.map 512 512 298 319 180 138 245.69 +47 maps/wc3maps/losttemple.map 512 512 323 215 162 251 188.46 +41 maps/wc3maps/losttemple.map 512 512 416 269 280 216 166.15 +34 maps/wc3maps/losttemple.map 512 512 341 189 222 230 139.74 +30 maps/wc3maps/losttemple.map 512 512 253 228 144 264 123.91 +9 maps/wc3maps/losttemple.map 512 512 84 258 106 234 39.56 +25 maps/wc3maps/losttemple.map 512 512 230 87 269 174 103.15 +55 maps/wc3maps/losttemple.map 512 512 206 262 406 314 221.54 +47 maps/wc3maps/losttemple.map 512 512 80 299 251 277 190.11 +18 maps/wc3maps/losttemple.map 512 512 426 379 365 409 74.01 +18 maps/wc3maps/losttemple.map 512 512 344 305 337 235 72.90 +46 maps/wc3maps/losttemple.map 512 512 232 287 76 278 187.43 +61 maps/wc3maps/losttemple.map 512 512 424 75 323 63 247.49 +24 maps/wc3maps/losttemple.map 512 512 281 231 201 186 98.64 +11 maps/wc3maps/losttemple.map 512 512 293 250 265 214 47.60 +18 maps/wc3maps/losttemple.map 512 512 145 283 94 310 73.90 +35 maps/wc3maps/losttemple.map 512 512 355 301 282 198 142.61 +78 maps/wc3maps/losttemple.map 512 512 68 253 336 142 313.98 +50 maps/wc3maps/losttemple.map 512 512 176 367 214 188 202.30 +30 maps/wc3maps/losttemple.map 512 512 317 200 419 250 122.71 +40 maps/wc3maps/losttemple.map 512 512 271 148 280 291 160.77 +31 maps/wc3maps/losttemple.map 512 512 236 256 306 193 126.30 +25 maps/wc3maps/losttemple.map 512 512 317 342 256 275 101.64 +57 maps/wc3maps/losttemple.map 512 512 385 309 181 363 231.34 +4 maps/wc3maps/losttemple.map 512 512 229 111 217 101 16.14 +40 maps/wc3maps/losttemple.map 512 512 248 296 191 183 160.63 +20 maps/wc3maps/losttemple.map 512 512 141 237 78 189 82.88 +53 maps/wc3maps/losttemple.map 512 512 74 203 260 210 213.75 +50 maps/wc3maps/losttemple.map 512 512 255 358 107 261 203.99 +31 maps/wc3maps/losttemple.map 512 512 234 160 157 254 125.89 +53 maps/wc3maps/losttemple.map 512 512 273 402 418 310 214.10 +30 maps/wc3maps/losttemple.map 512 512 94 366 129 304 120.54 +43 maps/wc3maps/losttemple.map 512 512 95 292 83 402 175.48 +95 maps/wc3maps/losttemple.map 512 512 150 378 352 121 381.90 +84 maps/wc3maps/losttemple.map 512 512 170 317 349 70 336.62 +40 maps/wc3maps/losttemple.map 512 512 208 323 88 224 161.59 +92 maps/wc3maps/losttemple.map 512 512 404 242 99 400 370.45 +40 maps/wc3maps/losttemple.map 512 512 339 289 208 367 163.31 +53 maps/wc3maps/losttemple.map 512 512 313 102 194 252 215.05 +18 maps/wc3maps/losttemple.map 512 512 48 85 102 54 74.46 +46 maps/wc3maps/losttemple.map 512 512 314 188 174 272 187.10 +74 maps/wc3maps/losttemple.map 512 512 416 291 224 89 296.17 +42 maps/wc3maps/losttemple.map 512 512 253 309 124 213 169.94 +88 maps/wc3maps/losttemple.map 512 512 132 333 390 148 352.20 +89 maps/wc3maps/losttemple.map 512 512 247 427 286 118 357.40 +15 maps/wc3maps/losttemple.map 512 512 160 126 187 76 61.18 +34 maps/wc3maps/losttemple.map 512 512 360 159 281 225 136.64 +67 maps/wc3maps/losttemple.map 512 512 109 320 353 254 271.34 +15 maps/wc3maps/losttemple.map 512 512 407 395 373 432 61.77 +48 maps/wc3maps/losttemple.map 512 512 396 246 234 172 192.65 +49 maps/wc3maps/losttemple.map 512 512 69 397 75 321 197.05 +93 maps/wc3maps/losttemple.map 512 512 186 114 222 376 373.42 +60 maps/wc3maps/losttemple.map 512 512 269 222 428 94 243.05 +57 maps/wc3maps/losttemple.map 512 512 425 117 253 120 230.38 +92 maps/wc3maps/losttemple.map 512 512 411 312 67 262 369.68 +45 maps/wc3maps/losttemple.map 512 512 438 69 326 162 183.79 +47 maps/wc3maps/losttemple.map 512 512 425 242 236 241 191.07 +56 maps/wc3maps/losttemple.map 512 512 254 154 61 233 225.72 +71 maps/wc3maps/losttemple.map 512 512 426 304 187 400 284.87 +18 maps/wc3maps/losttemple.map 512 512 119 301 190 295 75.97 +49 maps/wc3maps/losttemple.map 512 512 387 175 422 306 197.87 +83 maps/wc3maps/losttemple.map 512 512 339 88 171 336 333.89 +45 maps/wc3maps/losttemple.map 512 512 331 245 185 332 182.04 +9 maps/wc3maps/losttemple.map 512 512 204 353 167 346 39.90 +31 maps/wc3maps/losttemple.map 512 512 299 419 311 380 126.84 +57 maps/wc3maps/losttemple.map 512 512 426 219 293 98 228.71 +68 maps/wc3maps/losttemple.map 512 512 444 111 299 315 272.85 +44 maps/wc3maps/losttemple.map 512 512 148 257 255 365 178.42 +62 maps/wc3maps/losttemple.map 512 512 159 243 383 179 251.34 +21 maps/wc3maps/losttemple.map 512 512 326 290 312 371 86.80 +64 maps/wc3maps/losttemple.map 512 512 215 93 361 291 258.48 +71 maps/wc3maps/losttemple.map 512 512 79 218 344 272 287.37 +56 maps/wc3maps/losttemple.map 512 512 112 300 312 248 224.85 +94 maps/wc3maps/losttemple.map 512 512 137 391 327 105 379.35 +59 maps/wc3maps/losttemple.map 512 512 401 279 261 430 237.11 +80 maps/wc3maps/losttemple.map 512 512 218 137 140 399 320.01 +23 maps/wc3maps/losttemple.map 512 512 413 220 346 188 92.46 +31 maps/wc3maps/losttemple.map 512 512 308 403 229 450 127.21 +54 maps/wc3maps/losttemple.map 512 512 86 257 263 191 216.78 +92 maps/wc3maps/losttemple.map 512 512 338 77 72 287 370.56 +47 maps/wc3maps/losttemple.map 512 512 271 220 369 83 191.98 +82 maps/wc3maps/losttemple.map 512 512 66 333 264 116 328.89 +87 maps/wc3maps/losttemple.map 512 512 353 96 64 241 349.06 +41 maps/wc3maps/losttemple.map 512 512 133 365 120 212 167.50 +58 maps/wc3maps/losttemple.map 512 512 104 396 309 366 232.20 +64 maps/wc3maps/losttemple.map 512 512 171 286 308 122 256.62 +51 maps/wc3maps/losttemple.map 512 512 267 124 414 122 204.97 +22 maps/wc3maps/losttemple.map 512 512 312 164 297 119 91.70 +10 maps/wc3maps/losttemple.map 512 512 256 306 216 303 42.07 +22 maps/wc3maps/losttemple.map 512 512 317 205 265 218 89.87 +30 maps/wc3maps/losttemple.map 512 512 294 417 297 308 121.01 +74 maps/wc3maps/losttemple.map 512 512 340 375 105 262 296.45 +73 maps/wc3maps/losttemple.map 512 512 230 135 61 332 292.78 +93 maps/wc3maps/losttemple.map 512 512 327 117 174 423 375.48 +46 maps/wc3maps/losttemple.map 512 512 133 333 304 361 184.94 +22 maps/wc3maps/losttemple.map 512 512 154 259 115 332 89.74 +85 maps/wc3maps/losttemple.map 512 512 305 180 89 395 341.96 +68 maps/wc3maps/losttemple.map 512 512 374 292 139 376 272.72 +63 maps/wc3maps/losttemple.map 512 512 197 330 233 101 253.67 +59 maps/wc3maps/losttemple.map 512 512 204 352 415 315 236.27 +91 maps/wc3maps/losttemple.map 512 512 109 335 351 85 367.23 +98 maps/wc3maps/losttemple.map 512 512 436 320 62 328 395.54 +18 maps/wc3maps/losttemple.map 512 512 131 348 196 325 74.53 +18 maps/wc3maps/losttemple.map 512 512 281 193 250 235 74.80 +25 maps/wc3maps/losttemple.map 512 512 404 267 340 281 100.81 +54 maps/wc3maps/losttemple.map 512 512 230 435 329 258 218.01 +25 maps/wc3maps/losttemple.map 512 512 180 236 159 323 100.38 +24 maps/wc3maps/losttemple.map 512 512 272 370 204 434 99.78 +71 maps/wc3maps/losttemple.map 512 512 67 257 315 170 284.04 +28 maps/wc3maps/losttemple.map 512 512 252 314 158 264 114.71 +18 maps/wc3maps/losttemple.map 512 512 360 105 301 126 74.73 +65 maps/wc3maps/losttemple.map 512 512 375 293 137 237 261.20 +94 maps/wc3maps/losttemple.map 512 512 171 428 233 80 376.99 +14 maps/wc3maps/losttemple.map 512 512 152 255 102 231 59.94 +41 maps/wc3maps/losttemple.map 512 512 392 299 235 292 167.36 +78 maps/wc3maps/losttemple.map 512 512 265 109 182 390 315.97 +107 maps/wc3maps/losttemple.map 512 512 441 129 182 430 431.13 +62 maps/wc3maps/losttemple.map 512 512 104 337 319 256 248.55 +93 maps/wc3maps/losttemple.map 512 512 418 221 118 271 374.49 +65 maps/wc3maps/losttemple.map 512 512 193 418 195 177 261.71 +19 maps/wc3maps/losttemple.map 512 512 291 168 291 221 77.33 +71 maps/wc3maps/losttemple.map 512 512 143 266 388 169 285.18 +26 maps/wc3maps/losttemple.map 512 512 315 286 286 377 107.15 +67 maps/wc3maps/losttemple.map 512 512 411 113 248 312 271.79 +32 maps/wc3maps/losttemple.map 512 512 259 285 154 344 129.44 +35 maps/wc3maps/losttemple.map 512 512 276 188 238 306 143.70 +74 maps/wc3maps/losttemple.map 512 512 400 286 164 423 298.02 +36 maps/wc3maps/losttemple.map 512 512 268 365 243 228 147.36 +4 maps/wc3maps/losttemple.map 512 512 359 302 347 287 19.97 +31 maps/wc3maps/losttemple.map 512 512 226 296 230 196 125.80 +48 maps/wc3maps/losttemple.map 512 512 342 374 316 197 192.25 +6 maps/wc3maps/losttemple.map 512 512 240 290 238 264 26.83 +66 maps/wc3maps/losttemple.map 512 512 377 287 193 107 265.59 +70 maps/wc3maps/losttemple.map 512 512 72 276 332 288 282.37 +94 maps/wc3maps/losttemple.map 512 512 68 322 341 106 377.70 +73 maps/wc3maps/losttemple.map 512 512 211 433 394 231 294.20 +67 maps/wc3maps/losttemple.map 512 512 121 251 317 336 271.85 +64 maps/wc3maps/losttemple.map 512 512 104 283 280 421 257.76 +38 maps/wc3maps/losttemple.map 512 512 290 110 245 230 154.46 +43 maps/wc3maps/losttemple.map 512 512 207 255 324 135 175.49 +51 maps/wc3maps/losttemple.map 512 512 170 368 250 198 204.31 +67 maps/wc3maps/losttemple.map 512 512 80 226 90 443 269.39 +72 maps/wc3maps/losttemple.map 512 512 75 208 347 249 288.98 +22 maps/wc3maps/losttemple.map 512 512 244 405 286 334 89.57 +73 maps/wc3maps/losttemple.map 512 512 100 216 275 423 294.13 +42 maps/wc3maps/losttemple.map 512 512 294 90 353 228 168.88 +61 maps/wc3maps/losttemple.map 512 512 438 113 283 283 244.16 +16 maps/wc3maps/losttemple.map 512 512 82 228 149 226 67.83 +28 maps/wc3maps/losttemple.map 512 512 431 209 325 226 113.04 +33 maps/wc3maps/losttemple.map 512 512 109 220 230 226 135.08 +63 maps/wc3maps/losttemple.map 512 512 66 232 89 429 255.61 +48 maps/wc3maps/losttemple.map 512 512 359 239 293 73 193.34 +48 maps/wc3maps/losttemple.map 512 512 274 169 209 336 195.10 +4 maps/wc3maps/losttemple.map 512 512 416 103 428 117 18.97 +71 maps/wc3maps/losttemple.map 512 512 224 424 438 328 285.61 +37 maps/wc3maps/losttemple.map 512 512 102 319 159 209 149.43 +57 maps/wc3maps/losttemple.map 512 512 279 265 440 135 231.25 +48 maps/wc3maps/losttemple.map 512 512 202 151 184 327 195.88 +73 maps/wc3maps/losttemple.map 512 512 100 215 375 229 293.23 +45 maps/wc3maps/losttemple.map 512 512 370 176 301 324 180.10 +56 maps/wc3maps/losttemple.map 512 512 197 156 370 280 224.36 +68 maps/wc3maps/losttemple.map 512 512 191 316 341 145 275.79 +27 maps/wc3maps/losttemple.map 512 512 279 211 183 199 110.08 +56 maps/wc3maps/losttemple.map 512 512 257 240 184 437 227.24 +19 maps/wc3maps/losttemple.map 512 512 251 281 199 337 78.71 +68 maps/wc3maps/losttemple.map 512 512 290 365 140 271 273.42 +75 maps/wc3maps/losttemple.map 512 512 321 158 122 343 302.72 +43 maps/wc3maps/losttemple.map 512 512 169 429 283 315 172.94 +115 maps/wc3maps/losttemple.map 512 512 368 74 109 414 461.93 +77 maps/wc3maps/losttemple.map 512 512 253 315 440 89 308.73 +23 maps/wc3maps/losttemple.map 512 512 414 231 330 251 92.28 +38 maps/wc3maps/losttemple.map 512 512 442 280 331 189 152.79 +114 maps/wc3maps/losttemple.map 512 512 138 362 446 72 458.00 +85 maps/wc3maps/losttemple.map 512 512 207 398 407 166 343.10 +97 maps/wc3maps/losttemple.map 512 512 421 83 104 226 390.88 +80 maps/wc3maps/losttemple.map 512 512 275 422 259 121 322.50 +11 maps/wc3maps/losttemple.map 512 512 183 430 181 383 47.83 +33 maps/wc3maps/losttemple.map 512 512 266 170 346 82 134.61 +51 maps/wc3maps/losttemple.map 512 512 114 330 290 262 204.17 +19 maps/wc3maps/losttemple.map 512 512 123 213 83 272 79.67 +61 maps/wc3maps/losttemple.map 512 512 147 383 262 211 246.66 +105 maps/wc3maps/losttemple.map 512 512 402 251 75 447 421.84 +63 maps/wc3maps/losttemple.map 512 512 370 165 290 379 254.59 +13 maps/wc3maps/losttemple.map 512 512 243 87 284 122 55.50 +78 maps/wc3maps/losttemple.map 512 512 225 367 389 127 313.20 +21 maps/wc3maps/losttemple.map 512 512 83 269 142 237 86.56 +77 maps/wc3maps/losttemple.map 512 512 215 107 262 395 308.30 +3 maps/wc3maps/losttemple.map 512 512 207 254 215 245 12.31 +17 maps/wc3maps/losttemple.map 512 512 355 216 416 202 70.94 +33 maps/wc3maps/losttemple.map 512 512 346 271 283 379 135.75 +45 maps/wc3maps/losttemple.map 512 512 229 329 394 286 182.81 +46 maps/wc3maps/losttemple.map 512 512 229 425 104 385 187.89 +35 maps/wc3maps/losttemple.map 512 512 416 298 333 195 143.24 +76 maps/wc3maps/losttemple.map 512 512 218 309 427 116 305.35 +19 maps/wc3maps/losttemple.map 512 512 316 361 334 290 78.46 +58 maps/wc3maps/losttemple.map 512 512 180 298 196 120 232.55 +19 maps/wc3maps/losttemple.map 512 512 235 176 244 250 77.73 +39 maps/wc3maps/losttemple.map 512 512 326 202 433 87 159.91 +75 maps/wc3maps/losttemple.map 512 512 214 195 211 382 301.10 +85 maps/wc3maps/losttemple.map 512 512 376 129 239 412 341.40 +55 maps/wc3maps/losttemple.map 512 512 234 87 108 199 220.35 +74 maps/wc3maps/losttemple.map 512 512 183 211 426 293 296.02 +61 maps/wc3maps/losttemple.map 512 512 371 77 184 200 244.39 +85 maps/wc3maps/losttemple.map 512 512 276 387 312 77 341.48 +29 maps/wc3maps/losttemple.map 512 512 201 184 217 262 119.94 +97 maps/wc3maps/losttemple.map 512 512 411 240 138 264 390.18 +50 maps/wc3maps/losttemple.map 512 512 217 270 224 80 203.67 +48 maps/wc3maps/losttemple.map 512 512 147 341 312 288 192.23 +56 maps/wc3maps/losttemple.map 512 512 68 444 113 268 227.98 +50 maps/wc3maps/losttemple.map 512 512 377 244 175 244 202.83 +11 maps/wc3maps/losttemple.map 512 512 261 160 246 120 46.21 +55 maps/wc3maps/losttemple.map 512 512 272 208 77 257 221.54 +24 maps/wc3maps/losttemple.map 512 512 317 154 348 238 96.84 +31 maps/wc3maps/losttemple.map 512 512 145 275 251 225 126.71 +88 maps/wc3maps/losttemple.map 512 512 178 418 239 90 353.27 +95 maps/wc3maps/losttemple.map 512 512 281 122 152 433 383.42 +7 maps/wc3maps/losttemple.map 512 512 240 109 262 88 30.70 +15 maps/wc3maps/losttemple.map 512 512 277 284 290 325 63.50 +53 maps/wc3maps/losttemple.map 512 512 416 306 214 288 213.60 +6 maps/wc3maps/losttemple.map 512 512 396 165 412 144 27.63 +72 maps/wc3maps/losttemple.map 512 512 335 370 329 93 288.36 +53 maps/wc3maps/losttemple.map 512 512 179 370 246 183 215.92 +57 maps/wc3maps/losttemple.map 512 512 111 251 191 442 230.14 +78 maps/wc3maps/losttemple.map 512 512 318 165 109 360 313.79 +28 maps/wc3maps/losttemple.map 512 512 309 161 216 132 113.30 +15 maps/wc3maps/losttemple.map 512 512 121 86 70 64 60.11 +12 maps/wc3maps/losttemple.map 512 512 301 261 321 285 48.38 +11 maps/wc3maps/losttemple.map 512 512 158 144 144 103 46.80 +42 maps/wc3maps/losttemple.map 512 512 244 174 234 339 169.14 +66 maps/wc3maps/losttemple.map 512 512 317 234 154 416 265.86 +32 maps/wc3maps/losttemple.map 512 512 300 215 334 323 131.74 +52 maps/wc3maps/losttemple.map 512 512 163 443 81 299 211.44 +61 maps/wc3maps/losttemple.map 512 512 167 315 266 110 247.76 +74 maps/wc3maps/losttemple.map 512 512 139 357 334 183 296.95 +42 maps/wc3maps/losttemple.map 512 512 414 144 407 219 169.58 +64 maps/wc3maps/losttemple.map 512 512 313 395 166 215 256.71 +63 maps/wc3maps/losttemple.map 512 512 76 254 316 235 255.08 +20 maps/wc3maps/losttemple.map 512 512 269 250 340 221 83.01 +44 maps/wc3maps/losttemple.map 512 512 147 224 139 398 178.97 +32 maps/wc3maps/losttemple.map 512 512 155 302 281 308 129.31 +68 maps/wc3maps/losttemple.map 512 512 410 272 158 292 272.23 +78 maps/wc3maps/losttemple.map 512 512 287 73 137 326 315.13 +58 maps/wc3maps/losttemple.map 512 512 148 273 266 88 233.88 +12 maps/wc3maps/losttemple.map 512 512 116 396 150 360 50.08 +113 maps/wc3maps/losttemple.map 512 512 407 112 114 408 455.00 +46 maps/wc3maps/losttemple.map 512 512 327 180 320 362 184.90 +41 maps/wc3maps/losttemple.map 512 512 152 301 86 439 165.34 +67 maps/wc3maps/losttemple.map 512 512 316 61 240 296 268.82 +29 maps/wc3maps/losttemple.map 512 512 255 329 355 290 116.15 +54 maps/wc3maps/losttemple.map 512 512 297 111 329 294 218.21 +21 maps/wc3maps/losttemple.map 512 512 188 326 104 317 87.73 +21 maps/wc3maps/losttemple.map 512 512 191 305 267 313 84.49 +52 maps/wc3maps/losttemple.map 512 512 419 296 375 141 209.94 +6 maps/wc3maps/losttemple.map 512 512 175 285 180 307 24.07 +5 maps/wc3maps/losttemple.map 512 512 140 312 148 294 21.31 +54 maps/wc3maps/losttemple.map 512 512 99 385 263 272 216.66 +66 maps/wc3maps/losttemple.map 512 512 220 332 437 212 267.88 +96 maps/wc3maps/losttemple.map 512 512 132 263 376 173 385.30 +9 maps/wc3maps/losttemple.map 512 512 434 260 421 292 37.38 +63 maps/wc3maps/losttemple.map 512 512 215 349 380 181 253.92 +10 maps/wc3maps/losttemple.map 512 512 179 390 180 431 41.41 +66 maps/wc3maps/losttemple.map 512 512 331 99 332 350 264.28 +39 maps/wc3maps/losttemple.map 512 512 286 253 183 364 158.94 +62 maps/wc3maps/losttemple.map 512 512 271 408 323 184 248.85 +29 maps/wc3maps/losttemple.map 512 512 169 311 241 246 116.50 +25 maps/wc3maps/losttemple.map 512 512 428 131 344 178 103.47 +55 maps/wc3maps/losttemple.map 512 512 198 158 277 340 220.58 +62 maps/wc3maps/losttemple.map 512 512 90 219 324 254 248.50 +65 maps/wc3maps/losttemple.map 512 512 233 220 79 393 261.98 +80 maps/wc3maps/losttemple.map 512 512 80 304 386 273 322.98 +77 maps/wc3maps/losttemple.map 512 512 170 291 360 77 308.17 +77 maps/wc3maps/losttemple.map 512 512 312 368 281 106 311.53 +25 maps/wc3maps/losttemple.map 512 512 90 287 175 279 102.40 +62 maps/wc3maps/losttemple.map 512 512 253 294 343 87 251.31 +21 maps/wc3maps/losttemple.map 512 512 321 173 377 236 86.78 +39 maps/wc3maps/losttemple.map 512 512 224 160 254 307 159.43 +74 maps/wc3maps/losttemple.map 512 512 127 405 347 252 296.26 +17 maps/wc3maps/losttemple.map 512 512 130 346 196 335 70.56 +5 maps/wc3maps/losttemple.map 512 512 279 210 263 220 20.14 +49 maps/wc3maps/losttemple.map 512 512 356 230 204 337 197.49 +63 maps/wc3maps/losttemple.map 512 512 313 342 361 110 255.20 +28 maps/wc3maps/losttemple.map 512 512 244 208 205 114 113.67 +27 maps/wc3maps/losttemple.map 512 512 274 85 199 151 110.54 +15 maps/wc3maps/losttemple.map 512 512 148 230 182 274 62.77 +59 maps/wc3maps/losttemple.map 512 512 81 252 232 102 238.32 +8 maps/wc3maps/losttemple.map 512 512 200 244 232 248 33.66 +60 maps/wc3maps/losttemple.map 512 512 406 306 356 109 242.52 +42 maps/wc3maps/losttemple.map 512 512 213 222 104 336 170.28 +53 maps/wc3maps/losttemple.map 512 512 294 348 371 167 212.89 +0 maps/wc3maps/losttemple.map 512 512 362 235 365 233 3.83 +30 maps/wc3maps/losttemple.map 512 512 140 220 74 296 121.50 +52 maps/wc3maps/losttemple.map 512 512 400 188 226 244 209.50 +29 maps/wc3maps/losttemple.map 512 512 285 247 167 244 119.24 +48 maps/wc3maps/losttemple.map 512 512 389 127 285 271 194.11 +99 maps/wc3maps/losttemple.map 512 512 86 329 430 194 399.92 +59 maps/wc3maps/losttemple.map 512 512 247 128 253 362 237.31 +55 maps/wc3maps/losttemple.map 512 512 241 263 89 374 221.21 +47 maps/wc3maps/losttemple.map 512 512 410 235 247 304 191.58 +94 maps/wc3maps/losttemple.map 512 512 227 406 358 98 376.12 +89 maps/wc3maps/losttemple.map 512 512 72 414 191 119 357.36 +70 maps/wc3maps/losttemple.map 512 512 418 252 219 397 283.81 +91 maps/wc3maps/losttemple.map 512 512 87 430 303 193 366.93 +20 maps/wc3maps/losttemple.map 512 512 188 385 134 370 83.57 +109 maps/wc3maps/losttemple.map 512 512 88 439 325 113 438.81 +68 maps/wc3maps/losttemple.map 512 512 195 361 211 122 273.02 +77 maps/wc3maps/losttemple.map 512 512 163 351 441 273 310.31 +47 maps/wc3maps/losttemple.map 512 512 270 425 302 254 191.47 +35 maps/wc3maps/losttemple.map 512 512 205 138 117 228 140.51 +64 maps/wc3maps/losttemple.map 512 512 435 189 361 78 258.04 +105 maps/wc3maps/losttemple.map 512 512 72 447 404 247 423.43 +39 maps/wc3maps/losttemple.map 512 512 268 255 415 286 159.84 +88 maps/wc3maps/losttemple.map 512 512 384 141 69 230 354.21 +72 maps/wc3maps/losttemple.map 512 512 102 388 355 302 288.62 +73 maps/wc3maps/losttemple.map 512 512 86 258 319 368 292.91 +58 maps/wc3maps/losttemple.map 512 512 361 117 216 274 235.22 +59 maps/wc3maps/losttemple.map 512 512 118 243 284 311 236.08 +25 maps/wc3maps/losttemple.map 512 512 132 249 205 319 101.99 +40 maps/wc3maps/losttemple.map 512 512 407 127 272 167 162.34 +68 maps/wc3maps/losttemple.map 512 512 129 318 239 89 275.15 +46 maps/wc3maps/losttemple.map 512 512 216 265 108 386 185.65 +97 maps/wc3maps/losttemple.map 512 512 418 233 101 409 389.90 +34 maps/wc3maps/losttemple.map 512 512 199 447 265 343 136.61 +19 maps/wc3maps/losttemple.map 512 512 233 331 214 265 76.70 +24 maps/wc3maps/losttemple.map 512 512 145 217 86 269 98.25 +13 maps/wc3maps/losttemple.map 512 512 324 375 334 326 55.14 +3 maps/wc3maps/losttemple.map 512 512 240 166 251 171 13.07 +37 maps/wc3maps/losttemple.map 512 512 404 204 310 141 151.75 +24 maps/wc3maps/losttemple.map 512 512 112 227 191 178 99.30 +52 maps/wc3maps/losttemple.map 512 512 254 367 427 283 208.62 +34 maps/wc3maps/losttemple.map 512 512 405 280 277 271 139.18 +73 maps/wc3maps/losttemple.map 512 512 283 180 67 345 292.55 +20 maps/wc3maps/losttemple.map 512 512 355 119 282 101 80.46 +36 maps/wc3maps/losttemple.map 512 512 291 213 167 269 147.20 +56 maps/wc3maps/losttemple.map 512 512 115 409 288 383 225.31 +36 maps/wc3maps/losttemple.map 512 512 139 246 273 233 144.36 +78 maps/wc3maps/losttemple.map 512 512 164 442 231 159 314.07 +62 maps/wc3maps/losttemple.map 512 512 280 351 81 246 250.78 +112 maps/wc3maps/losttemple.map 512 512 78 432 309 99 449.19 +22 maps/wc3maps/losttemple.map 512 512 298 158 309 119 89.36 +78 maps/wc3maps/losttemple.map 512 512 271 368 295 98 312.37 +38 maps/wc3maps/losttemple.map 512 512 322 212 195 149 153.10 +45 maps/wc3maps/losttemple.map 512 512 125 318 264 212 183.49 +72 maps/wc3maps/losttemple.map 512 512 408 289 167 205 289.85 +65 maps/wc3maps/losttemple.map 512 512 202 406 79 200 260.46 +26 maps/wc3maps/losttemple.map 512 512 324 271 331 369 105.97 +42 maps/wc3maps/losttemple.map 512 512 377 246 330 376 168.88 +33 maps/wc3maps/losttemple.map 512 512 317 216 254 116 132.72 +51 maps/wc3maps/losttemple.map 512 512 314 133 164 252 206.32 +54 maps/wc3maps/losttemple.map 512 512 111 265 291 292 219.43 +60 maps/wc3maps/losttemple.map 512 512 346 295 237 99 241.15 +62 maps/wc3maps/losttemple.map 512 512 431 283 232 202 251.76 +66 maps/wc3maps/losttemple.map 512 512 328 271 111 373 265.11 +63 maps/wc3maps/losttemple.map 512 512 77 310 299 238 254.65 +59 maps/wc3maps/losttemple.map 512 512 203 435 327 257 236.98 +67 maps/wc3maps/losttemple.map 512 512 66 231 327 234 270.53 +90 maps/wc3maps/losttemple.map 512 512 392 142 139 353 360.32 +42 maps/wc3maps/losttemple.map 512 512 168 301 277 400 168.75 +37 maps/wc3maps/losttemple.map 512 512 302 401 214 464 150.84 +41 maps/wc3maps/losttemple.map 512 512 361 226 226 154 164.82 +10 maps/wc3maps/losttemple.map 512 512 232 125 272 121 41.66 +26 maps/wc3maps/losttemple.map 512 512 436 213 335 215 106.80 +21 maps/wc3maps/losttemple.map 512 512 239 265 163 288 86.11 +66 maps/wc3maps/losttemple.map 512 512 217 398 385 233 265.53 +23 maps/wc3maps/losttemple.map 512 512 252 302 161 295 95.56 +29 maps/wc3maps/losttemple.map 512 512 249 220 146 259 119.15 +60 maps/wc3maps/losttemple.map 512 512 372 289 425 90 243.32 +76 maps/wc3maps/losttemple.map 512 512 201 369 392 148 305.39 +78 maps/wc3maps/losttemple.map 512 512 320 147 55 257 313.05 +51 maps/wc3maps/losttemple.map 512 512 362 296 184 366 206.99 +91 maps/wc3maps/losttemple.map 512 512 129 358 435 215 365.23 +71 maps/wc3maps/losttemple.map 512 512 213 189 230 425 285.85 +70 maps/wc3maps/losttemple.map 512 512 397 224 160 333 282.15 +56 maps/wc3maps/losttemple.map 512 512 203 379 351 220 227.33 +52 maps/wc3maps/losttemple.map 512 512 357 107 252 265 211.45 +30 maps/wc3maps/losttemple.map 512 512 355 163 410 219 120.01 +47 maps/wc3maps/losttemple.map 512 512 241 291 412 280 189.64 +86 maps/wc3maps/losttemple.map 512 512 380 240 79 343 344.25 +92 maps/wc3maps/losttemple.map 512 512 283 416 277 73 371.17 +42 maps/wc3maps/losttemple.map 512 512 126 321 240 205 170.25 +74 maps/wc3maps/losttemple.map 512 512 326 374 113 245 299.28 +94 maps/wc3maps/losttemple.map 512 512 195 395 330 79 378.02 +14 maps/wc3maps/losttemple.map 512 512 381 128 435 116 58.97 +39 maps/wc3maps/losttemple.map 512 512 78 223 172 326 157.75 +68 maps/wc3maps/losttemple.map 512 512 278 244 76 395 273.92 +51 maps/wc3maps/losttemple.map 512 512 266 254 150 380 207.66 +58 maps/wc3maps/losttemple.map 512 512 149 292 366 255 232.33 +85 maps/wc3maps/losttemple.map 512 512 432 258 115 298 342.68 +55 maps/wc3maps/losttemple.map 512 512 336 319 177 220 220.55 +41 maps/wc3maps/losttemple.map 512 512 180 201 179 359 166.70 +58 maps/wc3maps/losttemple.map 512 512 276 323 82 417 232.94 +78 maps/wc3maps/losttemple.map 512 512 309 171 134 386 314.43 +76 maps/wc3maps/losttemple.map 512 512 376 300 82 319 306.01 +14 maps/wc3maps/losttemple.map 512 512 265 217 226 199 58.50 +35 maps/wc3maps/losttemple.map 512 512 240 302 210 189 142.66 +74 maps/wc3maps/losttemple.map 512 512 173 305 307 64 299.82 +82 maps/wc3maps/losttemple.map 512 512 323 125 83 308 330.45 +74 maps/wc3maps/losttemple.map 512 512 275 92 148 337 297.61 +91 maps/wc3maps/losttemple.map 512 512 435 189 121 319 367.85 +72 maps/wc3maps/losttemple.map 512 512 202 190 286 422 290.12 +40 maps/wc3maps/losttemple.map 512 512 314 115 237 211 160.70 +45 maps/wc3maps/losttemple.map 512 512 134 345 301 313 180.25 +69 maps/wc3maps/losttemple.map 512 512 312 235 101 250 276.33 +54 maps/wc3maps/losttemple.map 512 512 414 148 391 307 219.52 +61 maps/wc3maps/losttemple.map 512 512 187 183 414 211 246.88 +51 maps/wc3maps/losttemple.map 512 512 89 203 259 288 205.21 +77 maps/wc3maps/losttemple.map 512 512 279 437 234 145 310.64 +52 maps/wc3maps/losttemple.map 512 512 328 206 268 393 211.85 +44 maps/wc3maps/losttemple.map 512 512 254 226 428 239 179.38 +48 maps/wc3maps/losttemple.map 512 512 71 327 83 410 194.92 +25 maps/wc3maps/losttemple.map 512 512 347 289 277 295 101.30 +64 maps/wc3maps/losttemple.map 512 512 145 242 396 230 257.63 +17 maps/wc3maps/losttemple.map 512 512 169 235 110 213 68.11 +29 maps/wc3maps/losttemple.map 512 512 326 192 277 288 119.81 +64 maps/wc3maps/losttemple.map 512 512 352 254 188 424 256.09 +71 maps/wc3maps/losttemple.map 512 512 108 312 197 111 286.39 +8 maps/wc3maps/losttemple.map 512 512 207 228 233 210 33.46 +49 maps/wc3maps/losttemple.map 512 512 299 191 307 370 198.88 +41 maps/wc3maps/losttemple.map 512 512 253 212 323 337 167.85 +100 maps/wc3maps/losttemple.map 512 512 420 130 127 356 403.01 +41 maps/wc3maps/losttemple.map 512 512 278 295 365 167 167.55 +49 maps/wc3maps/losttemple.map 512 512 202 335 318 208 198.76 +49 maps/wc3maps/losttemple.map 512 512 419 191 393 118 199.94 +14 maps/wc3maps/losttemple.map 512 512 94 132 67 86 59.53 +49 maps/wc3maps/losttemple.map 512 512 394 310 224 366 198.99 +44 maps/wc3maps/losttemple.map 512 512 247 265 410 300 179.98 +69 maps/wc3maps/losttemple.map 512 512 225 167 102 369 277.39 +103 maps/wc3maps/losttemple.map 512 512 354 184 58 423 412.57 +26 maps/wc3maps/losttemple.map 512 512 390 296 351 207 106.33 +44 maps/wc3maps/losttemple.map 512 512 256 121 219 283 179.67 +77 maps/wc3maps/losttemple.map 512 512 85 430 321 257 310.59 +91 maps/wc3maps/losttemple.map 512 512 317 96 237 422 367.42 +76 maps/wc3maps/losttemple.map 512 512 347 121 82 212 307.66 +89 maps/wc3maps/losttemple.map 512 512 314 114 113 351 358.92 +37 maps/wc3maps/losttemple.map 512 512 142 216 279 241 149.84 +99 maps/wc3maps/losttemple.map 512 512 210 117 69 439 397.66 +34 maps/wc3maps/losttemple.map 512 512 241 240 109 224 139.46 +23 maps/wc3maps/losttemple.map 512 512 194 248 166 327 95.28 +44 maps/wc3maps/losttemple.map 512 512 290 239 430 335 179.76 +44 maps/wc3maps/losttemple.map 512 512 259 105 367 148 178.15 +81 maps/wc3maps/losttemple.map 512 512 174 236 439 96 326.30 +38 maps/wc3maps/losttemple.map 512 512 216 372 158 340 155.64 +40 maps/wc3maps/losttemple.map 512 512 256 252 221 103 163.50 +24 maps/wc3maps/losttemple.map 512 512 90 200 84 294 97.31 +40 maps/wc3maps/losttemple.map 512 512 206 117 274 244 162.68 +5 maps/wc3maps/losttemple.map 512 512 271 201 292 199 21.83 +67 maps/wc3maps/losttemple.map 512 512 300 330 212 101 271.89 +27 maps/wc3maps/losttemple.map 512 512 296 415 284 311 111.46 +40 maps/wc3maps/losttemple.map 512 512 281 358 368 231 163.04 +39 maps/wc3maps/losttemple.map 512 512 179 415 104 340 159.78 +34 maps/wc3maps/losttemple.map 512 512 78 290 120 371 139.95 +34 maps/wc3maps/losttemple.map 512 512 272 246 323 144 139.27 +33 maps/wc3maps/losttemple.map 512 512 321 251 217 324 135.41 +32 maps/wc3maps/losttemple.map 512 512 189 348 81 395 129.23 +64 maps/wc3maps/losttemple.map 512 512 269 231 120 404 256.92 +39 maps/wc3maps/losttemple.map 512 512 238 286 302 165 159.23 +17 maps/wc3maps/losttemple.map 512 512 147 322 210 342 71.28 +38 maps/wc3maps/losttemple.map 512 512 373 221 402 109 155.89 +82 maps/wc3maps/losttemple.map 512 512 99 341 288 107 329.86 +94 maps/wc3maps/losttemple.map 512 512 73 439 225 127 377.45 +93 maps/wc3maps/losttemple.map 512 512 413 325 95 411 375.36 +38 maps/wc3maps/losttemple.map 512 512 92 207 232 236 155.33 +10 maps/wc3maps/losttemple.map 512 512 279 242 299 208 42.28 +66 maps/wc3maps/losttemple.map 512 512 242 403 404 263 264.09 +60 maps/wc3maps/losttemple.map 512 512 192 305 424 295 240.28 +25 maps/wc3maps/losttemple.map 512 512 240 147 296 213 100.33 +38 maps/wc3maps/losttemple.map 512 512 402 123 280 199 155.82 +38 maps/wc3maps/losttemple.map 512 512 289 196 419 258 155.68 +89 maps/wc3maps/losttemple.map 512 512 323 89 292 422 358.27 +37 maps/wc3maps/losttemple.map 512 512 187 315 332 330 151.21 +96 maps/wc3maps/losttemple.map 512 512 432 251 98 352 387.74 +33 maps/wc3maps/losttemple.map 512 512 240 258 308 166 135.98 +29 maps/wc3maps/losttemple.map 512 512 249 216 345 272 119.20 +22 maps/wc3maps/losttemple.map 512 512 328 269 398 224 88.64 +15 maps/wc3maps/losttemple.map 512 512 221 319 209 280 61.43 +33 maps/wc3maps/losttemple.map 512 512 406 110 307 139 134.71 +15 maps/wc3maps/losttemple.map 512 512 397 144 428 95 61.84 +33 maps/wc3maps/losttemple.map 512 512 398 292 334 371 135.12 +70 maps/wc3maps/losttemple.map 512 512 416 266 154 229 282.25 +32 maps/wc3maps/losttemple.map 512 512 317 126 224 197 131.78 +32 maps/wc3maps/losttemple.map 512 512 341 253 404 164 131.50 +32 maps/wc3maps/losttemple.map 512 512 296 179 413 145 131.91 +60 maps/wc3maps/losttemple.map 512 512 318 260 104 283 242.10 +29 maps/wc3maps/losttemple.map 512 512 214 253 102 235 119.46 +32 maps/wc3maps/losttemple.map 512 512 261 353 189 251 131.82 +92 maps/wc3maps/losttemple.map 512 512 433 301 105 400 369.01 +69 maps/wc3maps/losttemple.map 512 512 150 216 405 217 277.78 +87 maps/wc3maps/losttemple.map 512 512 184 386 376 124 348.46 +21 maps/wc3maps/losttemple.map 512 512 323 181 305 252 85.73 +9 maps/wc3maps/losttemple.map 512 512 350 347 378 370 37.53 +32 maps/wc3maps/losttemple.map 512 512 262 389 348 308 130.68 +73 maps/wc3maps/losttemple.map 512 512 183 265 431 156 293.74 +60 maps/wc3maps/losttemple.map 512 512 194 191 99 392 243.87 +14 maps/wc3maps/losttemple.map 512 512 134 303 183 322 56.87 +23 maps/wc3maps/losttemple.map 512 512 250 205 178 262 95.61 +94 maps/wc3maps/losttemple.map 512 512 309 94 226 424 379.88 +32 maps/wc3maps/losttemple.map 512 512 224 297 281 399 131.47 +29 maps/wc3maps/losttemple.map 512 512 379 222 393 146 119.92 +5 maps/wc3maps/losttemple.map 512 512 232 285 218 268 22.80 +28 maps/wc3maps/losttemple.map 512 512 250 284 231 197 115.21 +19 maps/wc3maps/losttemple.map 512 512 359 293 428 311 76.46 +16 maps/wc3maps/losttemple.map 512 512 279 231 279 297 66.00 +28 maps/wc3maps/losttemple.map 512 512 340 266 378 173 115.18 +28 maps/wc3maps/losttemple.map 512 512 237 261 208 158 115.01 +63 maps/wc3maps/losttemple.map 512 512 305 64 230 285 252.07 +66 maps/wc3maps/losttemple.map 512 512 328 214 113 310 264.14 +28 maps/wc3maps/losttemple.map 512 512 278 284 366 219 115.51 +100 maps/wc3maps/losttemple.map 512 512 75 282 371 125 402.56 +65 maps/wc3maps/losttemple.map 512 512 301 153 75 200 263.31 +24 maps/wc3maps/losttemple.map 512 512 317 314 288 277 99.60 +27 maps/wc3maps/losttemple.map 512 512 180 256 262 185 111.41 +75 maps/wc3maps/losttemple.map 512 512 307 144 293 414 302.31 +94 maps/wc3maps/losttemple.map 512 512 427 314 119 249 378.88 +27 maps/wc3maps/losttemple.map 512 512 284 278 190 321 111.81 +64 maps/wc3maps/losttemple.map 512 512 221 124 418 273 259.89 +17 maps/wc3maps/losttemple.map 512 512 238 124 197 179 71.98 +100 maps/wc3maps/losttemple.map 512 512 398 230 83 431 400.60 +27 maps/wc3maps/losttemple.map 512 512 354 246 431 323 111.24 +76 maps/wc3maps/losttemple.map 512 512 303 348 431 94 307.02 +27 maps/wc3maps/losttemple.map 512 512 327 225 331 118 111.97 +27 maps/wc3maps/losttemple.map 512 512 186 370 255 427 110.77 +26 maps/wc3maps/losttemple.map 512 512 315 234 422 233 107.41 +26 maps/wc3maps/losttemple.map 512 512 324 160 324 267 107.83 +14 maps/wc3maps/losttemple.map 512 512 165 277 145 325 56.28 +26 maps/wc3maps/losttemple.map 512 512 189 304 293 311 107.73 +26 maps/wc3maps/losttemple.map 512 512 219 328 229 231 107.28 +69 maps/wc3maps/losttemple.map 512 512 219 83 398 266 278.82 +23 maps/wc3maps/losttemple.map 512 512 122 213 196 173 94.71 +23 maps/wc3maps/losttemple.map 512 512 133 229 207 178 95.12 +23 maps/wc3maps/losttemple.map 512 512 263 370 279 287 95.14 +23 maps/wc3maps/losttemple.map 512 512 324 307 377 243 95.33 +17 maps/wc3maps/losttemple.map 512 512 400 443 436 387 70.91 +23 maps/wc3maps/losttemple.map 512 512 269 248 178 259 95.56 +75 maps/wc3maps/losttemple.map 512 512 270 80 412 309 303.63 +22 maps/wc3maps/losttemple.map 512 512 320 158 286 95 91.14 +17 maps/wc3maps/losttemple.map 512 512 169 278 209 333 71.57 +95 maps/wc3maps/losttemple.map 512 512 102 388 367 161 382.46 +103 maps/wc3maps/losttemple.map 512 512 156 433 333 100 412.42 +17 maps/wc3maps/losttemple.map 512 512 142 289 112 235 71.70 +62 maps/wc3maps/losttemple.map 512 512 405 227 256 86 251.34 +17 maps/wc3maps/losttemple.map 512 512 327 178 391 166 70.63 +16 maps/wc3maps/losttemple.map 512 512 235 298 226 234 67.73 +16 maps/wc3maps/losttemple.map 512 512 322 244 271 285 67.98 +75 maps/wc3maps/losttemple.map 512 512 137 370 205 124 302.59 +62 maps/wc3maps/losttemple.map 512 512 355 244 181 405 251.23 +16 maps/wc3maps/losttemple.map 512 512 144 274 109 298 67.49 +16 maps/wc3maps/losttemple.map 512 512 297 85 315 139 67.36 +16 maps/wc3maps/losttemple.map 512 512 240 351 262 397 67.66 +16 maps/wc3maps/losttemple.map 512 512 318 293 318 360 67.00 +16 maps/wc3maps/losttemple.map 512 512 297 333 281 394 67.63 +12 maps/wc3maps/losttemple.map 512 512 392 438 419 400 49.18 +82 maps/wc3maps/losttemple.map 512 512 420 330 116 325 330.78 +93 maps/wc3maps/losttemple.map 512 512 167 447 260 114 372.11 +16 maps/wc3maps/losttemple.map 512 512 209 416 267 435 67.63 +15 maps/wc3maps/losttemple.map 512 512 249 303 308 302 63.56 +15 maps/wc3maps/losttemple.map 512 512 318 143 310 203 63.31 +14 maps/wc3maps/losttemple.map 512 512 329 304 385 297 58.90 +13 maps/wc3maps/losttemple.map 512 512 350 207 383 249 55.67 +61 maps/wc3maps/losttemple.map 512 512 228 416 410 286 246.98 +13 maps/wc3maps/losttemple.map 512 512 169 244 193 198 55.94 +81 maps/wc3maps/losttemple.map 512 512 278 211 73 433 325.66 +69 maps/wc3maps/losttemple.map 512 512 103 326 278 144 279.09 +13 maps/wc3maps/losttemple.map 512 512 258 280 278 327 55.87 +78 maps/wc3maps/losttemple.map 512 512 236 348 334 80 314.69 +13 maps/wc3maps/losttemple.map 512 512 355 306 407 309 55.73 +13 maps/wc3maps/losttemple.map 512 512 262 353 247 304 55.21 +12 maps/wc3maps/losttemple.map 512 512 201 174 206 127 51.90 +12 maps/wc3maps/losttemple.map 512 512 190 209 229 178 51.84 +12 maps/wc3maps/losttemple.map 512 512 323 171 333 124 51.14 +12 maps/wc3maps/losttemple.map 512 512 288 170 274 149 51.38 +80 maps/wc3maps/losttemple.map 512 512 341 385 310 123 323.08 +12 maps/wc3maps/losttemple.map 512 512 201 399 228 433 51.04 +76 maps/wc3maps/losttemple.map 512 512 293 97 331 374 307.18 +12 maps/wc3maps/losttemple.map 512 512 251 203 216 166 51.50 +12 maps/wc3maps/losttemple.map 512 512 283 336 321 367 50.84 +118 maps/wc3maps/losttemple.map 512 512 432 66 132 380 472.24 +76 maps/wc3maps/losttemple.map 512 512 192 420 310 178 307.75 +69 maps/wc3maps/losttemple.map 512 512 320 85 144 270 276.65 +80 maps/wc3maps/losttemple.map 512 512 324 132 268 429 323.51 +4 maps/wc3maps/losttemple.map 512 512 267 388 270 371 18.24 +11 maps/wc3maps/losttemple.map 512 512 264 384 273 428 47.73 +86 maps/wc3maps/losttemple.map 512 512 258 97 59 334 345.20 +11 maps/wc3maps/losttemple.map 512 512 121 354 96 378 47.83 +93 maps/wc3maps/losttemple.map 512 512 427 232 75 259 372.74 +3 maps/wc3maps/losttemple.map 512 512 250 169 248 183 14.83 +8 maps/wc3maps/losttemple.map 512 512 220 143 237 124 33.56 +11 maps/wc3maps/losttemple.map 512 512 204 393 206 437 47.31 +11 maps/wc3maps/losttemple.map 512 512 259 215 275 176 47.97 +11 maps/wc3maps/losttemple.map 512 512 235 345 269 316 47.18 +10 maps/wc3maps/losttemple.map 512 512 246 329 203 330 43.41 +10 maps/wc3maps/losttemple.map 512 512 140 319 106 339 43.46 +10 maps/wc3maps/losttemple.map 512 512 263 188 246 222 43.38 +10 maps/wc3maps/losttemple.map 512 512 266 306 302 323 43.04 +75 maps/wc3maps/losttemple.map 512 512 317 185 220 439 302.46 +10 maps/wc3maps/losttemple.map 512 512 280 282 265 314 43.04 +10 maps/wc3maps/losttemple.map 512 512 298 77 290 117 43.31 +79 maps/wc3maps/losttemple.map 512 512 367 182 109 304 316.74 +90 maps/wc3maps/losttemple.map 512 512 147 248 431 81 363.13 +9 maps/wc3maps/losttemple.map 512 512 157 326 162 289 39.07 +76 maps/wc3maps/losttemple.map 512 512 162 339 284 85 304.53 +9 maps/wc3maps/losttemple.map 512 512 279 265 293 299 39.80 +9 maps/wc3maps/losttemple.map 512 512 319 105 286 120 39.21 +8 maps/wc3maps/losttemple.map 512 512 320 104 350 91 35.38 +8 maps/wc3maps/losttemple.map 512 512 219 159 244 134 35.36 +8 maps/wc3maps/losttemple.map 512 512 347 114 362 85 35.21 +75 maps/wc3maps/losttemple.map 512 512 229 106 424 323 303.63 +104 maps/wc3maps/losttemple.map 512 512 62 440 422 299 418.40 +99 maps/wc3maps/losttemple.map 512 512 138 399 306 81 396.62 +8 maps/wc3maps/losttemple.map 512 512 273 368 275 403 35.83 +8 maps/wc3maps/losttemple.map 512 512 299 352 268 340 35.97 +4 maps/wc3maps/losttemple.map 512 512 346 89 356 74 19.14 +8 maps/wc3maps/losttemple.map 512 512 247 272 218 287 35.21 +7 maps/wc3maps/losttemple.map 512 512 93 403 71 425 31.11 +7 maps/wc3maps/losttemple.map 512 512 390 289 411 311 30.70 +75 maps/wc3maps/losttemple.map 512 512 375 279 94 224 303.78 +7 maps/wc3maps/losttemple.map 512 512 282 319 260 341 31.11 +7 maps/wc3maps/losttemple.map 512 512 199 156 191 128 31.31 +7 maps/wc3maps/losttemple.map 512 512 202 416 171 416 31.00 +7 maps/wc3maps/losttemple.map 512 512 82 244 78 214 31.66 +7 maps/wc3maps/losttemple.map 512 512 322 164 321 195 31.41 +7 maps/wc3maps/losttemple.map 512 512 379 145 400 123 30.70 +6 maps/wc3maps/losttemple.map 512 512 227 202 201 205 27.24 +6 maps/wc3maps/losttemple.map 512 512 383 242 403 260 27.46 +6 maps/wc3maps/losttemple.map 512 512 88 260 98 237 27.14 +126 maps/wc3maps/losttemple.map 512 512 70 379 438 94 507.14 +95 maps/wc3maps/losttemple.map 512 512 404 194 80 285 383.88 +85 maps/wc3maps/losttemple.map 512 512 316 79 215 367 342.72 +104 maps/wc3maps/losttemple.map 512 512 333 103 81 380 417.11 +73 maps/wc3maps/losttemple.map 512 512 263 350 410 116 294.89 +69 maps/wc3maps/losttemple.map 512 512 404 306 288 81 278.91 +6 maps/wc3maps/losttemple.map 512 512 185 269 196 257 27.24 +6 maps/wc3maps/losttemple.map 512 512 193 154 168 147 27.90 +6 maps/wc3maps/losttemple.map 512 512 271 362 261 385 27.14 +5 maps/wc3maps/losttemple.map 512 512 225 432 206 441 22.73 +5 maps/wc3maps/losttemple.map 512 512 182 288 181 272 23.14 +5 maps/wc3maps/losttemple.map 512 512 233 234 222 215 23.56 +112 maps/wc3maps/losttemple.map 512 512 432 97 94 243 448.62 +5 maps/wc3maps/losttemple.map 512 512 277 202 269 188 23.41 +5 maps/wc3maps/losttemple.map 512 512 184 204 162 207 23.24 +71 maps/wc3maps/losttemple.map 512 512 88 243 358 272 287.81 +5 maps/wc3maps/losttemple.map 512 512 369 160 381 141 23.97 +4 maps/wc3maps/losttemple.map 512 512 137 319 118 320 19.41 +4 maps/wc3maps/losttemple.map 512 512 266 303 283 309 19.49 +4 maps/wc3maps/losttemple.map 512 512 271 256 285 244 18.97 +72 maps/wc3maps/losttemple.map 512 512 319 140 105 300 291.79 +88 maps/wc3maps/losttemple.map 512 512 328 138 218 370 353.76 +4 maps/wc3maps/losttemple.map 512 512 264 297 263 313 19.00 +3 maps/wc3maps/losttemple.map 512 512 100 329 87 333 14.66 +3 maps/wc3maps/losttemple.map 512 512 263 403 263 418 15.00 +3 maps/wc3maps/losttemple.map 512 512 378 151 373 148 15.66 +3 maps/wc3maps/losttemple.map 512 512 175 279 168 267 14.90 +2 maps/wc3maps/losttemple.map 512 512 304 252 312 244 11.31 +91 maps/wc3maps/losttemple.map 512 512 66 437 211 132 365.06 +2 maps/wc3maps/losttemple.map 512 512 295 236 291 245 11.24 +2 maps/wc3maps/losttemple.map 512 512 283 390 289 399 11.49 +2 maps/wc3maps/losttemple.map 512 512 221 253 232 253 11.00 +2 maps/wc3maps/losttemple.map 512 512 347 252 349 263 11.83 +2 maps/wc3maps/losttemple.map 512 512 268 335 274 344 11.49 +93 maps/wc3maps/losttemple.map 512 512 87 300 355 92 372.70 +2 maps/wc3maps/losttemple.map 512 512 229 283 218 285 11.83 +2 maps/wc3maps/losttemple.map 512 512 254 103 262 95 11.31 +2 maps/wc3maps/losttemple.map 512 512 173 322 166 313 11.90 +2 maps/wc3maps/losttemple.map 512 512 89 236 78 234 11.83 +1 maps/wc3maps/losttemple.map 512 512 200 153 204 147 7.66 +1 maps/wc3maps/losttemple.map 512 512 262 162 256 158 7.66 +1 maps/wc3maps/losttemple.map 512 512 250 297 255 292 7.07 +1 maps/wc3maps/losttemple.map 512 512 315 90 310 85 7.07 +90 maps/wc3maps/losttemple.map 512 512 91 233 424 163 361.99 +82 maps/wc3maps/losttemple.map 512 512 417 254 136 348 329.05 +1 maps/wc3maps/losttemple.map 512 512 404 138 409 133 7.07 +100 maps/wc3maps/losttemple.map 512 512 102 418 399 197 402.01 +1 maps/wc3maps/losttemple.map 512 512 218 388 217 381 7.41 +1 maps/wc3maps/losttemple.map 512 512 91 324 84 326 7.83 +82 maps/wc3maps/losttemple.map 512 512 195 406 197 120 331.68 +1 maps/wc3maps/losttemple.map 512 512 157 254 150 254 7.00 +1 maps/wc3maps/losttemple.map 512 512 103 207 98 202 7.07 +1 maps/wc3maps/losttemple.map 512 512 350 283 355 287 6.66 +0 maps/wc3maps/losttemple.map 512 512 182 296 182 293 3.00 +0 maps/wc3maps/losttemple.map 512 512 340 304 342 306 2.83 +0 maps/wc3maps/losttemple.map 512 512 412 304 415 305 3.41 +0 maps/wc3maps/losttemple.map 512 512 398 275 401 274 3.41 +0 maps/wc3maps/losttemple.map 512 512 339 273 338 276 3.41 +80 maps/wc3maps/losttemple.map 512 512 411 117 133 219 320.84 +0 maps/wc3maps/losttemple.map 512 512 303 83 306 83 3.00 +72 maps/wc3maps/losttemple.map 512 512 149 334 333 143 291.82 +0 maps/wc3maps/losttemple.map 512 512 325 361 327 363 2.83 +0 maps/wc3maps/losttemple.map 512 512 279 312 281 310 2.83 +0 maps/wc3maps/losttemple.map 512 512 268 311 268 314 3.00 +72 maps/wc3maps/losttemple.map 512 512 280 359 327 90 291.78 +71 maps/wc3maps/losttemple.map 512 512 337 144 126 308 287.96 +87 maps/wc3maps/losttemple.map 512 512 286 407 349 92 348.55 +90 maps/wc3maps/losttemple.map 512 512 146 376 364 155 360.83 +80 maps/wc3maps/losttemple.map 512 512 421 88 305 360 320.05 +99 maps/wc3maps/losttemple.map 512 512 412 139 92 268 399.63 +80 maps/wc3maps/losttemple.map 512 512 333 132 237 408 322.59 +117 maps/wc3maps/losttemple.map 512 512 427 97 101 376 469.00 +84 maps/wc3maps/losttemple.map 512 512 83 383 300 179 338.40 +98 maps/wc3maps/losttemple.map 512 512 405 143 59 260 394.46 +94 maps/wc3maps/losttemple.map 512 512 289 118 116 403 376.58 +82 maps/wc3maps/losttemple.map 512 512 315 164 208 374 329.15 +84 maps/wc3maps/losttemple.map 512 512 223 126 89 403 339.58 +88 maps/wc3maps/losttemple.map 512 512 82 437 371 292 354.33 +96 maps/wc3maps/losttemple.map 512 512 219 411 314 86 387.42 +79 maps/wc3maps/losttemple.map 512 512 169 417 309 175 317.69 +82 maps/wc3maps/losttemple.map 512 512 393 259 80 223 331.67 +79 maps/wc3maps/losttemple.map 512 512 287 435 89 225 318.37 +79 maps/wc3maps/losttemple.map 512 512 104 418 338 230 318.90 +86 maps/wc3maps/losttemple.map 512 512 430 318 140 391 347.45 +79 maps/wc3maps/losttemple.map 512 512 89 202 380 269 319.92 +79 maps/wc3maps/losttemple.map 512 512 226 306 445 104 319.07 +92 maps/wc3maps/losttemple.map 512 512 294 412 417 103 370.72 +87 maps/wc3maps/losttemple.map 512 512 354 268 80 439 350.10 +80 maps/wc3maps/losttemple.map 512 512 286 62 211 353 322.07 +84 maps/wc3maps/losttemple.map 512 512 140 304 431 195 336.15 +101 maps/wc3maps/losttemple.map 512 512 412 131 147 377 407.06 +107 maps/wc3maps/losttemple.map 512 512 268 95 74 443 428.36 +82 maps/wc3maps/losttemple.map 512 512 285 437 65 239 329.55 +89 maps/wc3maps/losttemple.map 512 512 109 250 391 253 358.62 +100 maps/wc3maps/losttemple.map 512 512 338 126 150 445 402.97 +79 maps/wc3maps/losttemple.map 512 512 81 267 312 88 316.27 +80 maps/wc3maps/losttemple.map 512 512 428 254 176 407 322.40 +97 maps/wc3maps/losttemple.map 512 512 131 260 433 325 390.68 +81 maps/wc3maps/losttemple.map 512 512 319 91 67 265 325.83 +93 maps/wc3maps/losttemple.map 512 512 72 206 423 260 374.20 +101 maps/wc3maps/losttemple.map 512 512 447 86 172 355 406.93 +87 maps/wc3maps/losttemple.map 512 512 83 242 403 198 349.54 +94 maps/wc3maps/losttemple.map 512 512 86 245 420 141 378.25 +109 maps/wc3maps/losttemple.map 512 512 102 415 364 107 438.20 +86 maps/wc3maps/losttemple.map 512 512 171 136 226 419 346.45 +89 maps/wc3maps/losttemple.map 512 512 74 224 396 133 359.69 +79 maps/wc3maps/losttemple.map 512 512 101 320 399 283 317.47 +83 maps/wc3maps/losttemple.map 512 512 171 375 285 93 333.32 +93 maps/wc3maps/losttemple.map 512 512 82 300 386 154 375.99 +102 maps/wc3maps/losttemple.map 512 512 440 100 84 202 411.50 +84 maps/wc3maps/losttemple.map 512 512 308 69 97 278 336.11 +96 maps/wc3maps/losttemple.map 512 512 360 94 285 442 385.69 +116 maps/wc3maps/losttemple.map 512 512 422 101 131 250 465.13 +92 maps/wc3maps/losttemple.map 512 512 121 353 316 73 370.73 +98 maps/wc3maps/losttemple.map 512 512 76 398 363 184 393.22 +92 maps/wc3maps/losttemple.map 512 512 296 75 240 404 370.38 +90 maps/wc3maps/losttemple.map 512 512 406 238 67 269 362.57 +89 maps/wc3maps/losttemple.map 512 512 358 68 75 248 357.56 +83 maps/wc3maps/losttemple.map 512 512 335 208 96 404 334.83 +79 maps/wc3maps/losttemple.map 512 512 70 426 220 170 318.72 +89 maps/wc3maps/losttemple.map 512 512 227 120 74 398 356.85 +82 maps/wc3maps/losttemple.map 512 512 237 125 103 399 329.50 +95 maps/wc3maps/losttemple.map 512 512 284 416 354 68 382.79 +83 maps/wc3maps/losttemple.map 512 512 350 72 196 326 334.19 +90 maps/wc3maps/losttemple.map 512 512 121 375 293 88 362.93 +81 maps/wc3maps/losttemple.map 512 512 421 282 110 311 327.15 +85 maps/wc3maps/losttemple.map 512 512 426 126 269 396 342.06 +114 maps/wc3maps/losttemple.map 512 512 100 394 424 113 458.55 +83 maps/wc3maps/losttemple.map 512 512 368 157 220 431 335.30 +96 maps/wc3maps/losttemple.map 512 512 418 139 212 421 387.83 +99 maps/wc3maps/losttemple.map 512 512 63 330 363 114 397.67 +84 maps/wc3maps/losttemple.map 512 512 126 375 329 144 337.93 +91 maps/wc3maps/losttemple.map 512 512 395 242 96 238 364.01 +81 maps/wc3maps/losttemple.map 512 512 338 132 193 393 327.16 +90 maps/wc3maps/losttemple.map 512 512 99 243 395 237 362.33 +86 maps/wc3maps/losttemple.map 512 512 372 154 143 371 345.83 +97 maps/wc3maps/losttemple.map 512 512 433 212 73 263 391.85 +86 maps/wc3maps/losttemple.map 512 512 427 203 112 212 345.24 +91 maps/wc3maps/losttemple.map 512 512 305 121 294 414 364.41 +103 maps/wc3maps/losttemple.map 512 512 438 329 83 424 415.89 +92 maps/wc3maps/losttemple.map 512 512 94 313 413 192 371.46 +114 maps/wc3maps/losttemple.map 512 512 93 416 343 78 456.20 +101 maps/wc3maps/losttemple.map 512 512 223 395 364 73 407.19 +91 maps/wc3maps/losttemple.map 512 512 426 97 150 295 367.97 +101 maps/wc3maps/losttemple.map 512 512 174 440 287 79 407.81 +100 maps/wc3maps/losttemple.map 512 512 70 438 314 163 401.26 +85 maps/wc3maps/losttemple.map 512 512 152 352 310 90 343.26 +90 maps/wc3maps/losttemple.map 512 512 299 166 68 397 363.59 +83 maps/wc3maps/losttemple.map 512 512 96 255 336 123 333.02 +100 maps/wc3maps/losttemple.map 512 512 132 262 362 99 400.96 +89 maps/wc3maps/losttemple.map 512 512 111 397 395 216 358.97 +86 maps/wc3maps/losttemple.map 512 512 436 303 99 313 345.28 +99 maps/wc3maps/losttemple.map 512 512 225 407 435 109 398.46 +88 maps/wc3maps/losttemple.map 512 512 245 407 419 128 355.17 +83 maps/wc3maps/losttemple.map 512 512 311 122 102 317 334.53 +98 maps/wc3maps/losttemple.map 512 512 407 307 70 438 394.58 +111 maps/wc3maps/losttemple.map 512 512 429 87 94 261 444.89 +104 maps/wc3maps/losttemple.map 512 512 420 85 220 394 418.49 +83 maps/wc3maps/losttemple.map 512 512 186 144 214 396 335.62 +81 maps/wc3maps/losttemple.map 512 512 373 148 150 313 327.75 +88 maps/wc3maps/losttemple.map 512 512 337 97 243 407 352.84 +101 maps/wc3maps/losttemple.map 512 512 411 188 108 248 404.12 +81 maps/wc3maps/losttemple.map 512 512 65 256 293 440 327.65 +88 maps/wc3maps/losttemple.map 512 512 78 323 411 278 355.78 +87 maps/wc3maps/losttemple.map 512 512 86 263 386 172 351.89 +81 maps/wc3maps/losttemple.map 512 512 332 140 226 414 327.66 +81 maps/wc3maps/losttemple.map 512 512 424 277 113 239 327.91 +84 maps/wc3maps/losttemple.map 512 512 173 150 159 448 338.61 +120 maps/wc3maps/losttemple.map 512 512 97 389 445 103 482.87 +107 maps/wc3maps/losttemple.map 512 512 303 105 99 431 431.00 +87 maps/wc3maps/losttemple.map 512 512 324 139 170 421 351.89 +95 maps/wc3maps/losttemple.map 512 512 90 383 432 320 382.18 +87 maps/wc3maps/losttemple.map 512 512 420 220 126 359 351.58 +102 maps/wc3maps/losttemple.map 512 512 88 423 417 225 411.60 +117 maps/wc3maps/losttemple.map 512 512 118 250 440 101 470.20 +85 maps/wc3maps/losttemple.map 512 512 297 425 405 152 340.95 +104 maps/wc3maps/losttemple.map 512 512 402 242 62 432 418.70 +98 maps/wc3maps/losttemple.map 512 512 174 405 322 80 394.16 +110 maps/wc3maps/losttemple.map 512 512 91 286 438 113 441.77 +108 maps/wc3maps/losttemple.map 512 512 433 296 61 444 433.30 +86 maps/wc3maps/losttemple.map 512 512 319 205 95 421 346.90 +97 maps/wc3maps/losttemple.map 512 512 411 135 104 313 388.93 +87 maps/wc3maps/losttemple.map 512 512 262 110 213 390 350.78 +84 maps/wc3maps/losttemple.map 512 512 290 124 184 393 339.41 +84 maps/wc3maps/losttemple.map 512 512 153 344 340 97 339.10 +105 maps/wc3maps/losttemple.map 512 512 94 420 347 128 420.81 +98 maps/wc3maps/losttemple.map 512 512 421 163 89 266 394.87 +101 maps/wc3maps/losttemple.map 512 512 149 363 434 110 407.37 +117 maps/wc3maps/losttemple.map 512 512 432 182 64 430 470.72 +98 maps/wc3maps/losttemple.map 512 512 83 375 296 125 394.99 +100 maps/wc3maps/losttemple.map 512 512 266 419 429 86 400.52 +98 maps/wc3maps/losttemple.map 512 512 322 150 80 421 393.50 +96 maps/wc3maps/losttemple.map 512 512 126 317 406 105 386.56 +96 maps/wc3maps/losttemple.map 512 512 382 130 96 267 386.91 +114 maps/wc3maps/losttemple.map 512 512 317 109 59 425 456.20 +104 maps/wc3maps/losttemple.map 512 512 411 106 128 361 418.50 +96 maps/wc3maps/losttemple.map 512 512 348 76 294 426 386.45 +95 maps/wc3maps/losttemple.map 512 512 98 246 401 201 383.92 +110 maps/wc3maps/losttemple.map 512 512 159 343 446 63 443.98 +96 maps/wc3maps/losttemple.map 512 512 204 443 286 106 385.75 +105 maps/wc3maps/losttemple.map 512 512 406 118 166 434 420.68 +116 maps/wc3maps/losttemple.map 512 512 393 129 92 437 466.65 +110 maps/wc3maps/losttemple.map 512 512 159 449 314 83 442.20 +98 maps/wc3maps/losttemple.map 512 512 212 398 286 73 395.41 +103 maps/wc3maps/losttemple.map 512 512 135 322 422 81 415.53 +113 maps/wc3maps/losttemple.map 512 512 341 153 66 448 455.27 +109 maps/wc3maps/losttemple.map 512 512 76 287 432 133 439.71 +95 maps/wc3maps/losttemple.map 512 512 289 123 214 379 380.54 +98 maps/wc3maps/losttemple.map 512 512 108 263 369 147 392.45 +124 maps/wc3maps/losttemple.map 512 512 349 65 82 439 499.24 +103 maps/wc3maps/losttemple.map 512 512 79 337 354 69 415.30 +97 maps/wc3maps/losttemple.map 512 512 113 355 352 81 391.74 +95 maps/wc3maps/losttemple.map 512 512 108 330 402 138 381.73 +120 maps/wc3maps/losttemple.map 512 512 72 427 339 72 480.24 +103 maps/wc3maps/losttemple.map 512 512 292 445 291 67 415.69 +106 maps/wc3maps/losttemple.map 512 512 418 87 329 425 425.07 +102 maps/wc3maps/losttemple.map 512 512 177 432 416 130 409.78 +99 maps/wc3maps/losttemple.map 512 512 315 73 222 401 399.49 +113 maps/wc3maps/losttemple.map 512 512 412 120 90 369 453.68 +108 maps/wc3maps/losttemple.map 512 512 251 85 57 434 432.87 +110 maps/wc3maps/losttemple.map 512 512 114 253 435 140 443.81 +107 maps/wc3maps/losttemple.map 512 512 427 123 115 272 428.87 +97 maps/wc3maps/losttemple.map 512 512 435 64 198 332 388.43 +102 maps/wc3maps/losttemple.map 512 512 394 239 63 425 408.04 +102 maps/wc3maps/losttemple.map 512 512 429 71 313 399 409.59 +97 maps/wc3maps/losttemple.map 512 512 428 108 183 393 391.75 +105 maps/wc3maps/losttemple.map 512 512 70 402 401 207 421.91 +101 maps/wc3maps/losttemple.map 512 512 80 383 430 255 405.36 +108 maps/wc3maps/losttemple.map 512 512 77 446 318 126 434.47 +101 maps/wc3maps/losttemple.map 512 512 323 161 85 439 405.87 +101 maps/wc3maps/losttemple.map 512 512 413 151 104 259 404.76 +106 maps/wc3maps/losttemple.map 512 512 96 373 319 71 424.87 +114 maps/wc3maps/losttemple.map 512 512 304 96 56 430 458.98 +106 maps/wc3maps/losttemple.map 512 512 59 425 425 278 426.89 +102 maps/wc3maps/losttemple.map 512 512 77 426 406 256 410.19 +99 maps/wc3maps/losttemple.map 512 512 182 428 409 128 399.30 +99 maps/wc3maps/losttemple.map 512 512 81 378 292 99 399.20 +113 maps/wc3maps/losttemple.map 512 512 93 453 303 105 455.49 +101 maps/wc3maps/losttemple.map 512 512 68 420 324 144 407.23 +113 maps/wc3maps/losttemple.map 512 512 443 103 148 388 454.38 +108 maps/wc3maps/losttemple.map 512 512 426 205 70 395 434.70 +111 maps/wc3maps/losttemple.map 512 512 343 76 175 445 444.69 +119 maps/wc3maps/losttemple.map 512 512 439 93 67 326 476.71 +122 maps/wc3maps/losttemple.map 512 512 81 426 430 123 490.91 +103 maps/wc3maps/losttemple.map 512 512 283 81 71 380 413.76 +108 maps/wc3maps/losttemple.map 512 512 66 442 329 131 435.17 +105 maps/wc3maps/losttemple.map 512 512 107 407 436 184 423.71 +112 maps/wc3maps/losttemple.map 512 512 364 79 88 389 450.68 +102 maps/wc3maps/losttemple.map 512 512 65 325 429 213 410.39 +116 maps/wc3maps/losttemple.map 512 512 95 442 329 89 464.57 +105 maps/wc3maps/losttemple.map 512 512 310 99 148 431 420.86 +104 maps/wc3maps/losttemple.map 512 512 71 419 414 235 419.22 +102 maps/wc3maps/losttemple.map 512 512 440 79 168 345 410.88 +112 maps/wc3maps/losttemple.map 512 512 214 384 442 73 450.33 +102 maps/wc3maps/losttemple.map 512 512 363 150 104 362 410.14 +107 maps/wc3maps/losttemple.map 512 512 308 112 344 455 428.42 +108 maps/wc3maps/losttemple.map 512 512 421 104 239 373 434.04 +109 maps/wc3maps/losttemple.map 512 512 383 141 78 400 438.06 +104 maps/wc3maps/losttemple.map 512 512 99 439 416 238 416.66 +104 maps/wc3maps/losttemple.map 512 512 444 102 154 361 416.61 +105 maps/wc3maps/losttemple.map 512 512 363 83 140 267 422.24 +111 maps/wc3maps/losttemple.map 512 512 300 92 65 430 447.64 +103 maps/wc3maps/losttemple.map 512 512 74 230 438 109 414.12 +106 maps/wc3maps/losttemple.map 512 512 433 74 300 430 426.83 +120 maps/wc3maps/losttemple.map 512 512 446 62 81 270 482.20 +106 maps/wc3maps/losttemple.map 512 512 93 427 385 158 425.68 +106 maps/wc3maps/losttemple.map 512 512 79 331 414 130 426.46 +111 maps/wc3maps/losttemple.map 512 512 438 75 142 357 445.03 +114 maps/wc3maps/losttemple.map 512 512 429 201 66 429 457.44 +109 maps/wc3maps/losttemple.map 512 512 139 399 433 139 436.16 +103 maps/wc3maps/losttemple.map 512 512 242 437 319 76 412.98 +110 maps/wc3maps/losttemple.map 512 512 68 434 334 115 443.83 +114 maps/wc3maps/losttemple.map 512 512 98 427 343 86 457.13 +121 maps/wc3maps/losttemple.map 512 512 424 80 63 329 486.98 +111 maps/wc3maps/losttemple.map 512 512 323 76 101 414 445.19 +106 maps/wc3maps/losttemple.map 512 512 364 150 105 404 425.54 +113 maps/wc3maps/losttemple.map 512 512 65 446 445 281 455.66 +107 maps/wc3maps/losttemple.map 512 512 440 73 261 429 430.14 +109 maps/wc3maps/losttemple.map 512 512 420 112 115 383 438.34 +106 maps/wc3maps/losttemple.map 512 512 93 300 431 116 425.73 +109 maps/wc3maps/losttemple.map 512 512 435 74 215 399 438.63 +118 maps/wc3maps/losttemple.map 512 512 194 441 441 73 475.58 +112 maps/wc3maps/losttemple.map 512 512 409 199 60 444 451.07 +127 maps/wc3maps/losttemple.map 512 512 444 91 85 413 511.71 +112 maps/wc3maps/losttemple.map 512 512 424 211 74 442 449.20 +113 maps/wc3maps/losttemple.map 512 512 311 67 76 422 455.27 +110 maps/wc3maps/losttemple.map 512 512 110 311 432 74 441.84 +114 maps/wc3maps/losttemple.map 512 512 434 93 110 356 456.96 +127 maps/wc3maps/losttemple.map 512 512 435 70 113 409 508.01 +108 maps/wc3maps/losttemple.map 512 512 307 106 69 399 432.00 +115 maps/wc3maps/losttemple.map 512 512 122 256 435 103 463.47 +110 maps/wc3maps/losttemple.map 512 512 428 112 109 374 443.93 +112 maps/wc3maps/losttemple.map 512 512 70 378 333 80 450.29 +117 maps/wc3maps/losttemple.map 512 512 447 108 112 247 469.55 +110 maps/wc3maps/losttemple.map 512 512 435 122 155 430 443.70 +124 maps/wc3maps/losttemple.map 512 512 430 75 98 390 499.38 +124 maps/wc3maps/losttemple.map 512 512 418 118 71 438 498.29 +127 maps/wc3maps/losttemple.map 512 512 422 73 89 396 509.55 +127 maps/wc3maps/losttemple.map 512 512 70 441 409 107 508.39 +123 maps/wc3maps/losttemple.map 512 512 110 240 433 65 492.42 +111 maps/wc3maps/losttemple.map 512 512 351 101 75 416 447.48 +111 maps/wc3maps/losttemple.map 512 512 358 65 100 376 446.47 +107 maps/wc3maps/losttemple.map 512 512 402 254 58 442 430.98 +123 maps/wc3maps/losttemple.map 512 512 414 84 99 402 493.28 +110 maps/wc3maps/losttemple.map 512 512 417 133 73 346 440.43 +109 maps/wc3maps/losttemple.map 512 512 307 101 75 423 438.60 +105 maps/wc3maps/losttemple.map 512 512 325 163 58 443 422.23 +113 maps/wc3maps/losttemple.map 512 512 418 93 181 444 454.44 +107 maps/wc3maps/losttemple.map 512 512 424 92 86 263 430.65 +112 maps/wc3maps/losttemple.map 512 512 105 329 437 79 451.37 +125 maps/wc3maps/losttemple.map 512 512 82 387 433 87 503.38 +107 maps/wc3maps/losttemple.map 512 512 87 418 306 94 430.53 +114 maps/wc3maps/losttemple.map 512 512 408 128 84 406 457.90 +108 maps/wc3maps/losttemple.map 512 512 433 219 84 422 433.09 +109 maps/wc3maps/losttemple.map 512 512 84 316 433 118 439.22 +109 maps/wc3maps/losttemple.map 512 512 444 117 205 438 438.64 +105 maps/wc3maps/losttemple.map 512 512 430 73 143 319 420.53 +111 maps/wc3maps/losttemple.map 512 512 349 131 89 442 445.64 +107 maps/wc3maps/losttemple.map 512 512 85 440 419 230 429.77 +106 maps/wc3maps/losttemple.map 512 512 106 329 437 121 427.84 +104 maps/wc3maps/losttemple.map 512 512 425 71 251 418 419.07 +108 maps/wc3maps/losttemple.map 512 512 426 73 293 442 434.03 +113 maps/wc3maps/losttemple.map 512 512 367 86 109 417 453.34 +106 maps/wc3maps/losttemple.map 512 512 73 401 297 113 426.90 +108 maps/wc3maps/losttemple.map 512 512 122 308 444 75 432.57 +112 maps/wc3maps/losttemple.map 512 512 378 135 78 424 451.93 +114 maps/wc3maps/losttemple.map 512 512 435 79 70 269 458.35 +111 maps/wc3maps/losttemple.map 512 512 70 416 311 93 447.43 +116 maps/wc3maps/losttemple.map 512 512 352 110 93 451 464.68 +113 maps/wc3maps/losttemple.map 512 512 81 410 368 129 453.27 +115 maps/wc3maps/losttemple.map 512 512 68 451 424 209 461.51 +127 maps/wc3maps/losttemple.map 512 512 442 104 82 429 511.61 +117 maps/wc3maps/losttemple.map 512 512 109 412 432 109 471.35 +123 maps/wc3maps/losttemple.map 512 512 415 116 92 444 495.77 +119 maps/wc3maps/losttemple.map 512 512 433 68 122 375 477.41 +112 maps/wc3maps/losttemple.map 512 512 418 78 124 345 450.43 +119 maps/wc3maps/losttemple.map 512 512 83 447 358 97 478.55 +117 maps/wc3maps/losttemple.map 512 512 84 405 421 125 469.38 +111 maps/wc3maps/losttemple.map 512 512 441 93 93 263 446.62 +116 maps/wc3maps/losttemple.map 512 512 422 158 65 382 466.19 +115 maps/wc3maps/losttemple.map 512 512 319 109 64 440 460.68 +123 maps/wc3maps/losttemple.map 512 512 71 327 431 69 492.06 +116 maps/wc3maps/losttemple.map 512 512 103 381 430 100 465.65 +118 maps/wc3maps/losttemple.map 512 512 125 404 416 88 475.58 +118 maps/wc3maps/losttemple.map 512 512 313 82 74 446 475.88 +117 maps/wc3maps/losttemple.map 512 512 117 411 423 106 471.87 +119 maps/wc3maps/losttemple.map 512 512 414 119 80 420 479.18 +127 maps/wc3maps/losttemple.map 512 512 431 114 64 420 510.15 +127 maps/wc3maps/losttemple.map 512 512 420 76 84 399 511.97 +121 maps/wc3maps/losttemple.map 512 512 75 429 399 115 485.70 +117 maps/wc3maps/losttemple.map 512 512 364 78 78 411 470.80 +121 maps/wc3maps/losttemple.map 512 512 433 93 101 403 485.01 +121 maps/wc3maps/losttemple.map 512 512 434 79 121 401 485.62 +117 maps/wc3maps/losttemple.map 512 512 436 87 177 443 468.55 +119 maps/wc3maps/losttemple.map 512 512 72 298 441 80 477.16 +127 maps/wc3maps/losttemple.map 512 512 73 335 445 62 511.44 +120 maps/wc3maps/losttemple.map 512 512 437 114 84 384 481.24 +119 maps/wc3maps/losttemple.map 512 512 426 82 64 316 479.43 +124 maps/wc3maps/losttemple.map 512 512 426 84 87 386 498.07 +118 maps/wc3maps/losttemple.map 512 512 440 134 86 381 472.71 +116 maps/wc3maps/losttemple.map 512 512 68 447 342 108 467.14 +117 maps/wc3maps/losttemple.map 512 512 417 162 75 434 471.65 +115 maps/wc3maps/losttemple.map 512 512 73 384 406 126 460.96 +116 maps/wc3maps/losttemple.map 512 512 400 115 89 417 467.72 +122 maps/wc3maps/losttemple.map 512 512 444 74 174 446 489.11 +120 maps/wc3maps/losttemple.map 512 512 124 399 441 81 483.28 +127 maps/wc3maps/losttemple.map 512 512 70 447 412 112 510.64 +121 maps/wc3maps/losttemple.map 512 512 136 260 444 102 484.88 +116 maps/wc3maps/losttemple.map 512 512 65 433 357 101 467.60 +116 maps/wc3maps/losttemple.map 512 512 95 427 411 126 465.87 +119 maps/wc3maps/losttemple.map 512 512 118 401 420 84 476.07 +119 maps/wc3maps/losttemple.map 512 512 376 127 66 440 479.38 +119 maps/wc3maps/losttemple.map 512 512 87 371 419 101 477.75 +118 maps/wc3maps/losttemple.map 512 512 424 130 83 409 472.97 +122 maps/wc3maps/losttemple.map 512 512 138 275 444 115 491.81 +124 maps/wc3maps/losttemple.map 512 512 419 85 95 414 498.60 +124 maps/wc3maps/losttemple.map 512 512 432 70 161 452 499.52 +118 maps/wc3maps/losttemple.map 512 512 380 129 67 438 475.55 +118 maps/wc3maps/losttemple.map 512 512 80 443 441 187 474.65 +123 maps/wc3maps/losttemple.map 512 512 357 75 70 437 495.52 +115 maps/wc3maps/losttemple.map 512 512 412 164 73 426 463.93 +115 maps/wc3maps/losttemple.map 512 512 420 84 103 240 463.37 +115 maps/wc3maps/losttemple.map 512 512 440 79 85 276 462.86 +127 maps/wc3maps/losttemple.map 512 512 423 91 77 415 511.84 +122 maps/wc3maps/losttemple.map 512 512 416 86 115 408 489.62 +118 maps/wc3maps/losttemple.map 512 512 70 397 421 137 475.10 +115 maps/wc3maps/losttemple.map 512 512 432 94 117 393 463.45 +122 maps/wc3maps/losttemple.map 512 512 89 283 443 61 489.71 +115 maps/wc3maps/losttemple.map 512 512 440 115 76 332 462.09 +121 maps/wc3maps/losttemple.map 512 512 162 449 442 85 485.25 diff --git a/node_modules/pathfinding/benchmark/test_cases.js b/node_modules/pathfinding/benchmark/test_cases.js new file mode 100644 index 0000000..0358669 --- /dev/null +++ b/node_modules/pathfinding/benchmark/test_cases.js @@ -0,0 +1,11 @@ +/** + * the `select` field indicates which scenarios in the `scen` file are chosen + * to be included in the benchmark. + */ +module.exports = [ + { + map: './map/64room_000.map', + scen: './scen/64room_000.map.scen', + select: [ 245, 1996 ] + }, +] diff --git a/node_modules/pathfinding/docs/contributor-guide/authors.md b/node_modules/pathfinding/docs/contributor-guide/authors.md new file mode 100644 index 0000000..a55393d --- /dev/null +++ b/node_modules/pathfinding/docs/contributor-guide/authors.md @@ -0,0 +1,22 @@ +# Authors + +This is the alphabetically sorted list of contributors to PathFinding.js: + +Anders Riutta
+Chris Khoo
+Gerjo
+Juan Pablo Canepa
+Mat Gadd
+Murilo Pereira
+Nathan Witmer
+rafaelcastrocouto
+Raminder Singh
+Ricardo Tomasi
+Rodrigo Navarro
+Rory O'Kane
+Stuart Lee
+surrim
+Tapio Vierros
+Thomas Hunter II
+Willem Mulder
+Xueqiao Xu diff --git a/node_modules/pathfinding/docs/contributor-guide/contributing.md b/node_modules/pathfinding/docs/contributor-guide/contributing.md new file mode 100644 index 0000000..1f44357 --- /dev/null +++ b/node_modules/pathfinding/docs/contributor-guide/contributing.md @@ -0,0 +1,4 @@ +If you have added a new feature or fixed a bug please open a pull request. + +Don't forget to add yourself to the +[list of contributors](https://github.com/qiao/PathFinding.js/blob/master/docs/contributor-guide/authors.md). \ No newline at end of file diff --git a/node_modules/pathfinding/docs/contributor-guide/developing.md b/node_modules/pathfinding/docs/contributor-guide/developing.md new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/pathfinding/docs/custom.css b/node_modules/pathfinding/docs/custom.css new file mode 100644 index 0000000..ae51b17 --- /dev/null +++ b/node_modules/pathfinding/docs/custom.css @@ -0,0 +1,18 @@ +/*This is a hack to prevent mkdocs from creating useless subheadings in table of +contents. +E.g. If there is a page called introduction.md and it contains the following: + +# Introduction +Blah Blah Blah + +Then mkdocs created a table of contents like this: + +Introduction + Introduction + +This hack hides the second level heading + +*/ +.toctree-l2 { + display: none; +} diff --git a/node_modules/pathfinding/docs/index.md b/node_modules/pathfinding/docs/index.md new file mode 100644 index 0000000..c8e13b0 --- /dev/null +++ b/node_modules/pathfinding/docs/index.md @@ -0,0 +1,15 @@ +#Welcome to PathFinding.js documentation + +Table of Contents + +* User Guide + * [Introduction](./user-guide/introduction.md) + * [Installation](./user-guide/installation.md) + * [Getting Started](./user-guide/getting-started.md) + * [Obstacles](./user-guide/obstacles.md) + * [Diagonal Movement](./user-guide/diagonal-movement.md) + * [FAQ](./user-guide/faq.md) +* Contributor Guide + * [Contributing](./contributor-guide/contributing.md) + * [Developing](./contributor-guide/developing.md) + * [Authors](./contributor-guide/authors.md) \ No newline at end of file diff --git a/node_modules/pathfinding/docs/user-guide/diagonal-movement.md b/node_modules/pathfinding/docs/user-guide/diagonal-movement.md new file mode 100644 index 0000000..47aeb29 --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/diagonal-movement.md @@ -0,0 +1,52 @@ +# Diagonal Movement +To disable diagonal movement you need to configure the finder. The finder takes +a configuration object with an option called `diagonalMovement`. Setting this +option to `DiagonalMovement.Never` will disable diagonal movement completely. +Let us try it. + +```javascript +var finder = new PF.AStarFinder({ + diagonalMovement: PF.DiagonalMovement.Never +}); +``` + +See that the path is straight now: + +![Screenshot](user-guide/images/DiagonalMovementDisabled.png) + +The `diagonalMovement` option can take any of the following values: + +* Always +* Never +* IfAtMostOneObstacle +* OnlyWhenNoObstacles + +To understand them consider the following four simple maps labelled A, B, C and +D. A has no obstacles for diagonal movement from green to orange cell, B and C +have one obstacle and D has two obstacles. + +![Screenshot](user-guide/images/DiagonalMaps.png) + +## Always +With this option PathFinding.js will always find a diagonal path, irrespective +of the obstacles when moving diagonally. + +![Screenshot](user-guide/images/AllMapsWithAPath.png) + +## Never +With this option PathFinding.js will only find straight paths and will never +find any diagonal paths. + +![Screenshot](user-guide/images/AllMapsWithStraightPaths.png) + +## IfAtMostOneObstacle +With this option PathFinding.js will find diagonal paths only if there is at +most one obstacle for the diagonal path. + +![Screenshot](user-guide/images/DiagonalPathsForAtMostOneObstacle.png) + +## OnlyWhenNoObstacles +With this option PathFinding.js will find diagonal paths only if there are no +obstacles for the diagonal path. + +![Screenshot](user-guide/images/DiagonalPathsForOnlyWhenNoObstacles.png) diff --git a/node_modules/pathfinding/docs/user-guide/faq.md b/node_modules/pathfinding/docs/user-guide/faq.md new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/pathfinding/docs/user-guide/getting-started.md b/node_modules/pathfinding/docs/user-guide/getting-started.md new file mode 100644 index 0000000..2433b2f --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/getting-started.md @@ -0,0 +1,52 @@ +# Getting Started +This section explains the basic usage of PathFinding.js. + +## Importing in Node.js +To import PathFinding.js in your file do: + +```javascript +var PF = require('pathfinding'); +``` + +## Including in Browser +To include PathFinding.js in your page, add a script tag to your page: + +```html + +``` + +## Finding a Path +To find a path you need a grid first. Create a 5 by 7 grid: + +```javascript +var grid = new PF.Grid(5, 7); +``` +This will create a grid which is walkable all over. + +![Screenshot](user-guide/images/5x7EmptyGrid.png) + +In this grid, the green cell at the top left is [0, 0] and the orange cell at +the bottom right is [4, 6]. + +Now create an instance of a finder. There are many finders available in +PathFinding.js but use the famous A* for now: + +```javascript +var finder = new PF.AStarFinder(); +``` + +Now find the path from the green cell to the orange cell: + +```javascript +var path = finder.findPath(0, 0, 4, 6, grid); +``` + +This will return the following path: + +```javascript +[[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [4, 5], [4, 6]] +``` + +Which when plotted on the grid looks like: + +![Screenshot](user-guide/images/5x7GridWithPath.png) \ No newline at end of file diff --git a/node_modules/pathfinding/docs/user-guide/images/5x7EmptyGrid.png b/node_modules/pathfinding/docs/user-guide/images/5x7EmptyGrid.png new file mode 100644 index 0000000000000000000000000000000000000000..1509a2b0ff5339eefd324aadd56f7713a6e1f3ed GIT binary patch literal 1214 zcmeAS@N?(olHy`uVBq!ia0vp^(}4IA2OE%FalkYXuz@(kesf*OvL4j`Yiz$3Dl zfkCqkgc+6I-0uMjN|v}rlmzFem6RtIr81P4m+NKbWfvzW7NqLs7p2dBXCnnP$lBAz zF{EP7+dCVxQbHNpKmOl&XR6`sQ=U7y%Ql@=d%kJHrSJ_xHT>Lyjso(>&WVTxKVcO! zDnFwX`DWWSHP=Ovo9<;l6xny6oGoo%eDU(%{CE0Kuk@?@c6Rgja{c#xmoI#r{do7} zt0(6eE$5cGJ5Y%gXF(f?Ty=dXYE$KNk?Mqwr5+e zIGh;aBr#2(O|>PFlOpERpV!aV@2xNVUwHcB^8ES#_U?)KH|NQ&r+Jeuzr7q=u{}Oc zuRbzPZ@m=%ey>kUKBkpzshqI8cGBvzX~h?dwqBd1QdnMJZktS*BapoD^v#<$x7WQs zHf`}`6JF0p@BY2}wsgv~__eV)yKa|lpa1;l_ClF(-S+IY-PE>u>9t>nZO;4VD{C(0 zfmnQ7Ubp=JfA%|fFWxC_4LI=iAn$4?%ur|d!9<+-=^xaa%TfH*FW|j*7(kVIXjk1EDqvZ|;OXk;vd$@?2>^=24qE^K literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/5x7GridWithObstacles.png b/node_modules/pathfinding/docs/user-guide/images/5x7GridWithObstacles.png new file mode 100644 index 0000000000000000000000000000000000000000..4b0d9d5d80501e013c67106f89123641e19e9d26 GIT binary patch literal 1282 zcmeAS@N?(olHy`uVBq!ia0vp^(}4IA2OE%FalkYXuz@(kesf*OvL4j`Yiz$3Dl zfkCqkgc+6I-0uMjN|v}rlmzFem6RtIr81P4m+NKbWfvzW7NqLs7p2dBXCnnPsNU1X zF{EP7+dCWcWKt#E9+taF-&9<-@p|i7w=QiLt~Zj3PuW(i(7CKwC@!M0$SH=$!(&Ow zL0*NU*-RdtE0%rdW7$~NapByB8QvEEz3zQBdHhcITg0!`>u1$kR`2{%uyb-#S>4S@ zzw^uQUn~6^eDZFh#5|SG-GAOa`Sthp+w1;u=e_vC^H=9p+0_;TL0r-H%vo<$3a8&+ z>&=%{EHO=>O|>PFGcm%65~j=758dtd@%06@`=7jMp3Z;o&EFm0ohON_mQR+sUw5~) zeD&qam%}f=-11`U%%e#geT2$?-d*>4pZ}*lPx2=9t5sK5M{mCQX78lck1fhPAL;GC zU3&NP>C>mvRm*2D``D}6MzI4SUiA63@4xoR_p0u{_th8wU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9`dcW}yFPG~i>(iC(2mOSX9iY=gvnn^{H8CSaYV*JcqpW*Z*rbHqi^R?mD&B75NHVzA8>7(8hs1V;ZpSXaaVzT=Qmo7 z=Iiv>;%#p#tl^R3<9^5ot)zh8O%aQrZT@^CXKY^o)ePJ?%t$u##fc)uD=A4_lu~>Z zRK?2!tU7R4_(2XIdk1ctW*rUMZMFh7vh^7#mz$leouxME5~c_PAIy=V}NW|*w|KLt;=JHz)x~`>i3H|_V*Mn zEUuTh0Yf_z&%T9udmg5KU#@*u5Py+xcfM8Owz&@m-*F4^PesWq`mwOc?9uGA?U*}c zDZ%tbB0nAWW&D-pJ&AZSr6pl~04yrt{|@w^Pp>L(C?t(!?686YRtzv+R(^+VB9z}c z9{IP+n4nq*OtBOZ@HT7>kDMq-uoM^F=|%dlbQDhR2&=_AQlY)`Nnp_rn3-4@(+!;- F{uhW#)FA)> literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/5x7GridWithPath.png b/node_modules/pathfinding/docs/user-guide/images/5x7GridWithPath.png new file mode 100644 index 0000000000000000000000000000000000000000..e78ff73e9c1f54642207b215cf7a31e4eddff074 GIT binary patch literal 2524 zcmai0dpy(KAOE_A=tgWPdfc^K(o=3NC3A^J%(c0eo>4 zwuEK2)T&j=5{V594+$f;{J#D9d%d1szw>&1&Ut^{pL0IvoX_XH&g*m47wNuXz3zGd z05*7fxcY%(F(_|U)`5LZmqRHyDB@i_Q7T|dS2=kF)KwEbLht}!k^NKT4FCB|21%VH zL~xQn_EZuf>TC=^AP}r#6EOG_QHe2D*t36>P3_kO7lwGc9zvy*PkxFx<1gLL|0X@R zP5joo;6}}H#1Hk(!h_5XhaEDFd(m;sGFkSu*yDd!nOypfdpjHzz$C?n?v2;*a*ORQ zZekpbkEE5N&cz-oBJPbh*_hYVD)!y^+n zf=CliWLR-}1eTA;d>v}d-}{Oc?RDnn-b@9i*w4@3!raw*2UF~bTT3UT`R%D!(Yz2- zt1Ytox_W>1#fKtpmq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ff --git a/node_modules/pathfinding/docs/user-guide/images/AllMapsWithStraightPaths.png b/node_modules/pathfinding/docs/user-guide/images/AllMapsWithStraightPaths.png new file mode 100644 index 0000000000000000000000000000000000000000..5bb084228975d5848b6bd8811511b7bf9aa07447 GIT binary patch literal 2070 zcma)7c~lYz6X($INZqn^*DKpB+ziDQ%|ugE%kV5OR4TC$W79m)(1cLi5_e0#%tSJ6 zHE+cuZ}C8_%vQ9-iv+wfi8a(xDG~kL@1O6z@1L)EZ|2SX-n^Ojn>X_&^^AwJnu?AJ z002-!op$m90D#bK-%V-9wq^5mwgG?w(E;V7v@K*M9Bn&RjyxSe1ON`*{zrlP7bfp) zgW54C{bRf%@G+#|=nw#jL^35@y+XVc92sI75gnQ%vC#nlAoo#DCw$@_eH2i`d`a59 z%TmX`R5Bap=nkri{rrNb1UL@Jn3;j@JK}h@?hsVe-v~oMUGHGs5=4lbJQ8AzF~W zIy}cER+yKUx0!2A658yQwT`a)QKySly$4N>H|^u3hQCIJEJah{CkAG}LSZ zeAR?exqh@g6v<>V%LXu}bnD(LL1TfF&_b(x+Dq$v?CyJ0KW94~IHm&KrJRtocJ>2>ThNy3p7bNwDtJYZYDyPp( zI=v|Nw)$2c|6%JrxiSAOlMtB&Y`2Ze3+TS)K1172 z7hBav+^Y=AD{$n{_)n1ssZ`kAyLWpy9L_&Iy~@mOLc90HOLS4A6H&5B>XIT69*aiW zez;yS+R!R29|_2_sl4L0f483EeVT%E*Ma?AXU$SiNACG1sC?bMZNIkvGi4Sl1BmIg zqVz310pCSYcgIFjyOT1qlTn}W`U9;lJIL?XET`7qX&Pq_(JQd6D>FHN;F{qRfuEcx z_uKk>&El0`6;)Qed`vnqsSdWzP`7q(e15;mgS#QynpV=TY10~udrt^ z5aZ7xh--T#m*X6}GBvNGJ-%V-|9cw4V1&x8?()p}+^D5b!}P%f`C)>`TPyRvPBRY~ zlK8&=FEAKfHX3C7U}I{o>|IO5<@SToOr|AKYCgYb*VoP%W266_lF_Qh?})m;6Wi_W zYPtm}+^U~E`xg|k(=_)V5)Ij0$tL-z@7zs>yF!OLA4t~A2I(nu%uC?708DBB!aUn# znXY~gGyt+rdfY54G8ey`(S(hG>Jka;lB7x88OOXf4be2mGcpWhyVE8VPh!d7zf{1m z_))+D&{n}ljjVPV*r8+-f!F2B%XYf%93lUyF}{~7aH!v503OZZg-dLG{@(A^d7j;W z4eXqnT=rZrRv2hMkj>kLO=sC1`&G7>_>@&WQ2exp!82r&k}M3<)B3|eOGZ;*whd`< zu=LqJ2JgmHkYuyy>;xLzsnFOW8x0)0C$@kht{5RJZ={KQ!yYh9^b#`9JwI8%MQT6q zzavumz<5&Y~6mtezWKCc~m7A;QGS#Uy(MU0V&Bm_;*#5i;$_ zYDV}qX;S^Kefbt`$A4P`^dd?RYT#cCiU+?S_3Q>A>Lbww=ALu5$}m7NgLeusp=7RU zQZQKJ@4WZ;wB)_y)XKmR1PI>5<70VQT7^`QW8130txT9OJ1+_J%*2}sRNFi<8z0jQ zJ|~(^bycKgG(}4PkZfuca3@>X;o9^)dZbRJja-p_OVg3M^lY970+V?)q@_to6f4c! zuHa(E;KfYUu{HRVk(ZDf?JuPa!7pnUaG6y#tJZ7P zJ^b_2<}Mo-;}T1Q(!Wz2k);X~TOi}_Bq+6u#rT5NwKHv$7FOql&qyzo zVssKU=wseNM8fYPS~+tRE&B{rFV=Mq(^2pM!a*3m+zEPXE|J0c>H3KcJ+mW1a)xMN w(Fk!EhK({4ATM%H7Uapb;$l{kPBJ$j4|@7|1IMC@wtqMPb<)GB$^o1FZ`pM25&!@I literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/DiagonalMaps.png b/node_modules/pathfinding/docs/user-guide/images/DiagonalMaps.png new file mode 100644 index 0000000000000000000000000000000000000000..ed0c24155269c6e9baddfcff0d6eb650451d4a31 GIT binary patch literal 1683 zcmcIlYdF&j82_8gWFd9BxQx@<$a88^k1nn!&1I!kmJVjDNHn`-)1)%$IhrPAbrhmQ zw1_#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oVPNh( z+q%}qhSXGX*ROj`x^9-^1_TiABR>A+xXGr-KduVaSi!7LE$=nY0(Q9d2fJIj!Ww~d z^s*k*`A}IkiWpT}BVc*a(TKfL4CnWj$k z=aiL?h_ZRJ>cv~*x_A)Mm`@s&Fv}A`Md4Sy{Th2|bpyg+fS-%RL#}Y-}I8)KY?9f|{IN V6MXmXGEo0O0IVMlBk(0%_#3}bIrabm literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/DiagonalMovementDisabled.png b/node_modules/pathfinding/docs/user-guide/images/DiagonalMovementDisabled.png new file mode 100644 index 0000000000000000000000000000000000000000..9dd569d430c245275decca08eead8128118543c5 GIT binary patch literal 2017 zcma)7eN@s{7-l=$a9TRILetDIcFH8(u{HaUanjI!(_oq@>HI)NkD}Os{Q1qvW>$-A zIAtcFc576jbfX$lhFC?Bl{22U@)H( zEAurkjq(fxZlGfc^n)-&Ns;DdeOuo1Ij+4Xq2Qtu zV&=deM`Lj4Pl?g9OfhFP@4l=Px%sB=0rB?pRn1)0g4bq(V>V-?YNUfW>F;a>Et0Ke|<$Au|S4GzlYl z9~}|~K@o>k6c%#*%Dw!c%EM%TtL#nU&9b)Sy@WOo6yY5N%Ek`y#hZ37VJ|=GZ{wW9 zrRiywQ~o{M!Km=D4y-A}@}j=i5l9IfC~zAXuGqBRcFx!{0v-q5*^5RmdBGW`fQ^2> z+$Qw&*@;TDB}UF}m>c33gLqU7#qEYjUx{}Yq2tpq50YAgCe9)A+-L8z8vL&&XwWf} zZ3q*i*pv}+qpr60dB|6mPnAWUwO>Oq$v!QYk_kQQZmmM~5BQ`Rqgmc5JFU96kzX1u z^3DtbSOFRDXMV%ta3hr; zW2W2{l3AVXym zd-}`Zt19`gtpBDv6zzCTu9b^KA_M8{4|45UWPAKQN@_|_uK*YLgt3qk8(; z(P#3cx}AItR?SrWIv-{8WzPs<$=t!U^Mr5jkmJXICR&b@Nov$34$wMXi3y{} zH2ibN>qlo8`7xI5Badfk1qssQ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w zRZLs&xgpi62pJYLn&lc~`o~Bf4#92)wzpTiNf=2or@54VYU&N%X~LjU!Pl9V#MCsmNCf%O78K)r{=Ps@} z@Q)&KZ1+nWFNY-(z@0%bbd(bNWfYil;HSvhebP+?2JWyhztag(cGz zdPi(mY{PHV&oqUr{}Q~_O7~3qf??t-&$MZGYmXdF1C>2mr1A)aZV!sd~%T8 zS{TVt-_CP^ddk!q0j3_=BjbZPn~J~BC070at!HY?ey z1<3~D6o19h+-%o&GevOC9X1tp3SbCKP-)U`NHqbrcW~Zc7tEe2fPZ(L#%H*p&OZCu zj6D&f2g_{P-N6BwcbO{lxUQaCVF$YrU!AcZ-%U3Cu->Slx6{+UUtKou%EW@+bkUQm;&BFXUa`EI^%w|PTfBqgR3JLuL@&C(xRv;P yqh6Qvr-;04G33hG*<)>-G`h;fF?sSr%wuJ{z0Y5t1Pi}K0IN$j=9Omd5B?1@KEaOw literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/DiagonalPathsForOnlyWhenNoObstacles.png b/node_modules/pathfinding/docs/user-guide/images/DiagonalPathsForOnlyWhenNoObstacles.png new file mode 100644 index 0000000000000000000000000000000000000000..d92a5f7af85f09fff2259ed9b90c8dc72be6c7c4 GIT binary patch literal 2594 zcmZ`*X)qgV7fviGQCe$VgjNwn?X@qh##X9o-y02~))1tXUL|cUbz7HKMQuf?TC3KC z+OK_Wt%*c@b|RFD;)c)t`OTg0%)Dpb=bY!vyfg1P&zvM%8*^T;7#IKm@LF2H>;M3u z-09t#3v}w+X2nhe01mW?r32TgJ?8RBJjL873s*D%a3%hq1C*xE{c#%nEyC0#!afuk zf$=Naon!rwm~`V|X6No2jO6Dzf6Hb%$F$CA8|TIhqxDy&7nfe& z+sYnuHBB^YG5Qinw?{~6)i`%#Pf`4|w6#xa&m(TTs+n%QO(>ZRUVfYThq$)#_#-lj zM4YU;XIyw5!P^jN#V`(jGDLO7etfQ5z2`E3hxRm&&CdSqgWuKC(sB|CP^xf`DR65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HpNnKTqzL&U6GCt&O5)iE*=iefKZD@Xsx)W^;Yhzt zKi?_h@ido`T8$fKOMV%a&uPzerGw#~Ojkt&@*Kc9bLJLii?8ghKrKEcVYH^LiGSP< z+>Ml~GkU&f#tc)~j#h($cWpx?Re42ykpn|Py0+$@`8`GNLyG)gHf1%5x2G440711BWZg0X~bw9as3Qan`Wn>kBFV4Sfc!!6=&0KWn|t4RRSmD)$fTm@Ze|mxfoCJ zi;N0ZjI-6}soG&ml}faltQ@wf&56bcvd7U{(xliR*Izdo6*jigU(d_o_K4{hOKdJR z0?=1JcThr8%G>b$ROM05+0@|D%hS}5!TOP~{c|t8%q`k~iftc{Fc%t=~$%eD>5oj14?!y}p+9FsyD-ojp1ROLG0q^`DZboEOE}%<0G6gUuu2m+?!Pb<`I`U$ literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/docs/user-guide/images/images.svg b/node_modules/pathfinding/docs/user-guide/images/images.svg new file mode 100644 index 0000000..3c69fbe --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/images/images.svg @@ -0,0 +1,2536 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A + B + C + D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Empty Grid + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Grid With Obstacles + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Grid With Obstacles & Path + Diagonal Movement Disabled + Diagonal Maps + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Grid With Path + + A + B + C + D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AllMapsWithPaths + + A + B + C + D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AllMapsWithStraightPaths + + A + B + C + D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DiagonalPathsForAtMostOneObstacle + + A + B + C + D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DiagonalPathsForOnlyWhenNoObstacles + + diff --git a/node_modules/pathfinding/docs/user-guide/installation.md b/node_modules/pathfinding/docs/user-guide/installation.md new file mode 100644 index 0000000..2c0ddfa --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/installation.md @@ -0,0 +1,109 @@ +# Installation +This section describes how to install PathFinding.js. + +## Using Package Managers +PathFinding.js supports installation using npm and bower command line tools. + +### For Server +[Node.js](http://nodejs.org/) is an environment for running javascript on the +server. [Download](http://nodejs.org/download/) and install Node.js for your OS +and confirm that it works from the command line: + +```bash +node -v +``` + +If Node.js was installed correctly this should print the installed version of] +Node.js. + +Node.js comes with a [Node Package Manager](https://www.npmjs.com/) command line +tool called _npm_. It is used to install packages for Node.js. Check that it +works: + +```bash +npm -v +``` + +This should print the installed version of npm. + +npm installs the packages in the current folder by default. Make sure you are +in your project folder before continuing: + +```bash +cd +``` + +Now you are ready to install PathFinding.js. The npm command to install +PathFinding.js is: + +```bash +npm install pathfinding +``` + +This will create a _node_modules_ folder inside the my_new_project folder. +PathFinding.js is now installed in the _pathfinding_ folder inside the +node_modules folder. + +### For Client +[Bower](http://bower.io/) is a front-end package manager. Install it by running +the command: + +```bash +npm install -g bower +``` + +Confirm that you can run the bower command: + +```bash +bower -v +``` + +This should print the installed version of bower. + +Navigate to your project folder: + +```bash +cd +``` + +Install pathfinding: + +```bash +bower install pathfinding +``` + +This will create a _bower_components_ folder inside the my_new_project folder. +PathFinding.js is now installed in the pathfinding folder inside the +bower_components folder. + +## Manual Installation +If you want to use the latest development version you will have to install +PathFinding.js manually. + +### For Server +[Download](https://github.com/qiao/PathFinding.js/archive/master.zip) the zip +from github and extract the contents into the node_modules folder. Don't forget +to rename the extracted folder from PathFinding.js-master to pathfinding. + +### For Client +[Download](https://github.com/qiao/PathFinding.js/archive/master.zip) the zip +from github, extract it in a temporary folder and navigate to this folder: + +```bash +cd +``` + +Now install all the dependencies of PathFinding.js: + +```bash +npm install +``` + +Now compile the browser builds: + +```bash +gulp compile +``` + +This will create _pathfinding-browser.js_ and _pathfinding-browser.min.js_ files +in the temp_folder/lib folder. You can use these files in your project now. \ No newline at end of file diff --git a/node_modules/pathfinding/docs/user-guide/introduction.md b/node_modules/pathfinding/docs/user-guide/introduction.md new file mode 100644 index 0000000..be377d3 --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/introduction.md @@ -0,0 +1,51 @@ +# Introduction + +PathFinding.js is a javascript library to find paths on a 2D square grid. It +works in both node.js and browser environments. + +```javascript +//Walkability matrix. Zero is walkable, One is not +var matrix = [ + [0, 0, 0, 1, 0], + [1, 0, 0, 0, 1], + [0, 0, 1, 0, 0], +]; +var grid = new PF.Grid(matrix); +var finder = new PF.AStarFinder(); +//Find path from (1, 2) to (4, 2) +var path = finder.findPath(1, 2, 4, 2, grid); +``` + +## Getting Help + +If you stumble upon a bug or don't understand some feature of PathFinding.js, +open an issue in the +[Issue Tracker](https://github.com/qiao/PathFinding.js/issues). + +Browsing the [source](https://github.com/qiao/PathFinding.js) might also help. +A great visualization of the different pathfinding algorithms is available +[here](http://qiao.github.io/PathFinding.js/visual/). + +## License + +PathFinding.js is released under the +[MIT License](http://opensource.org/licenses/mit-license.php). + +(c) 2011-2012 Xueqiao Xu + +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/node_modules/pathfinding/docs/user-guide/obstacles.md b/node_modules/pathfinding/docs/user-guide/obstacles.md new file mode 100644 index 0000000..4854481 --- /dev/null +++ b/node_modules/pathfinding/docs/user-guide/obstacles.md @@ -0,0 +1,44 @@ +# Obstacles +A grid without any obstacles is boring. Let us create a grid with obstacles: + +```javascript +var walkabilityMatrix = [[0, 0, 0, 0, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0], + [0, 1, 1, 1, 1], + [0, 0, 0, 0, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]; +var grid = new PF.Grid(matrix); +``` + +The _walkabilityMatrix_ defines which cells are walkable and which have +obstacles. Ones are obstacles and zeroes are walkable. Alternatively, you can +also set the obstacles on the grid by calling the `setWalkableAt` function: + +```javascript +var grid = new PF.Grid(5, 7); +grid.setWalkableAt(0, 1, false); +grid.setWalkableAt(1, 1, false); +grid.setWalkableAt(2, 1, false); +... +``` + +After setting the obstacles the grid should look like this. + +![Screenshot](user-guide/images/5x7GridWithObstacles.png) + +Let us find a path now. + +```javascript +var finder = new PF.AStarFinder(); +var path = finder.findPath(0, 0, 4, 6, grid); +``` + +PathFinding.js will find the following path: + +![Screenshot](user-guide/images/5x7GridWithObstaclesAndPath.png) + +Notice how the path moves diagonally where it can, thus making it shorter. This +may not be always desirable and you may want to create a path without any +diagonal movement. Read the next section to find out how to achieve that. diff --git a/node_modules/pathfinding/gulpfile.js b/node_modules/pathfinding/gulpfile.js new file mode 100644 index 0000000..fa129e9 --- /dev/null +++ b/node_modules/pathfinding/gulpfile.js @@ -0,0 +1,102 @@ +var gulp = require('gulp'), + uglify = require('gulp-uglify'), + rename = require('gulp-rename'), + browserify = require('gulp-browserify'), + concat = require('gulp-concat'), + mocha = require('gulp-mocha'), + shell = require('shelljs'), + del = require('del'), + jshint = require('gulp-jshint'), + stylish = require('jshint-stylish'), + semver = require('semver'), + jsonfile = require('jsonfile'), + inquirer = require("inquirer"), + fs = require('fs'); + +gulp.task('clean', function(cb) { + del('lib/**/*.*', cb); +}); + +gulp.task('browserify', ['clean'], function(cb) { + return gulp.src('./src/PathFinding.js') + .pipe(browserify({ standalone: 'PF' })) + .pipe(rename('pathfinding-browserified.js')) + .pipe(gulp.dest('./lib/'), cb); +}); + +gulp.task('uglify', ['browserify'], function(cb) { + return gulp.src('./lib/pathfinding-browserified.js') + .pipe(uglify()) + .pipe(rename('pathfinding-browser.min.js')) + .pipe(gulp.dest('./lib/'), cb); +}); + +gulp.task('scripts', ['clean', 'browserify', 'uglify'], function(cb) { + return gulp.src(['./src/banner', './lib/pathfinding-browserified.js']) + .pipe(concat('pathfinding-browser.js')) + .pipe(gulp.dest('./lib/'), cb); +}); + +gulp.task('compile', ['scripts'], function() { + del('./lib/pathfinding-browserified.js'); +}); + +gulp.task('test', function () { + return gulp.src('./test/**/*.js', {read: false}) + .pipe(mocha({reporter: 'spec', bail: true, globals: { should: require('should') }})); +}); + +gulp.task('bench', function() { + shell.exec('node benchmark/benchmark.js'); +}); + +gulp.task('lint', function() { + return gulp.src('./src/**/*.js') + .pipe(jshint()) + .pipe(jshint.reporter(stylish)) + .pipe(jshint.reporter('fail')); +}); + +gulp.task('release', ['compile'], function(cb) { + inquirer.prompt({ + type: 'list', + name: 'bumpType', + message: 'Which version do you want to bump?', + choices: ['patch', 'minor', 'major'], + //default is patch + default: 0 + }, function (result) { + var f = jsonfile.readFileSync('./package.json'); + f.version = semver.inc(f.version, result.bumpType); + jsonfile.writeFileSync('./package.json', f); + + shell.exec('git add .'); + shell.exec('git commit -m "Bumping version to ' + f.version + '"'); + shell.exec('git push origin master'); + shell.exec('git tag -a ' + f.version + ' -m "Creating tag for version ' + f.version + '"'); + shell.exec('git push origin ' + f.version); + shell.exec('npm publish'); + + shell.exec('git clone https://github.com/imor/pathfinding-bower.git release'); + process.chdir('release'); + fs.writeFileSync('pathfinding-browser.js', fs.readFileSync('../lib/pathfinding-browser.js')); + fs.writeFileSync('pathfinding-browser.min.js', fs.readFileSync('../lib/pathfinding-browser.min.js')); + + f = jsonfile.readFileSync('bower.json'); + f.version = semver.inc(f.version, result.bumpType); + jsonfile.writeFileSync('bower.json', f); + + shell.exec('git add .'); + shell.exec('git commit -m "Bumping version to ' + f.version + '"'); + shell.exec('git push origin master'); + shell.exec('git tag -a ' + f.version + ' -m "Creating tag for version ' + f.version + '"'); + shell.exec('git push origin ' + f.version); + + process.chdir('../'); + del('release'); + del('lib/**/*.*', cb); + }); +}); + +gulp.task('default', ['lint', 'test', 'compile'], function() { +}); diff --git a/node_modules/pathfinding/index.js b/node_modules/pathfinding/index.js new file mode 100644 index 0000000..abe2c0a --- /dev/null +++ b/node_modules/pathfinding/index.js @@ -0,0 +1 @@ +module.exports = require('./src/PathFinding'); diff --git a/node_modules/pathfinding/mkdocs.yml b/node_modules/pathfinding/mkdocs.yml new file mode 100644 index 0000000..cd41674 --- /dev/null +++ b/node_modules/pathfinding/mkdocs.yml @@ -0,0 +1,18 @@ +site_name: PathFinding.js +repo_url: https://github.com/qiao/PathFinding.js +site_description: PathFinding.js is a javascript library to find paths on a 2D square grid +site_favicon: favicon.ico +site_author: Raminder Singh + +pages: +- [index.md, Home] +- ['user-guide/introduction.md', 'User Guide', 'Introduction'] +- ['user-guide/installation.md', 'User Guide', 'Installation'] +- ['user-guide/getting-started.md', 'User Guide', 'Getting Started'] +- ['user-guide/obstacles.md', 'User Guide', 'Obstacles'] +- ['user-guide/diagonal-movement.md', 'User Guide', 'Diagonal Movement'] +- ['user-guide/faq.md', 'User Guide', 'FAQ'] +- ['contributor-guide/contributing.md', 'Contributor Guide', 'Contributing'] +- ['contributor-guide/developing.md', 'Contributor Guide', 'Developing'] +- ['contributor-guide/authors.md', 'Contributor Guide', 'Authors'] +theme: readthedocs \ No newline at end of file diff --git a/node_modules/pathfinding/package.json b/node_modules/pathfinding/package.json new file mode 100644 index 0000000..9477e46 --- /dev/null +++ b/node_modules/pathfinding/package.json @@ -0,0 +1 @@ +{"name":"pathfinding","version":"0.4.18","description":"Comprehensive pathfinding library for grid based games","homepage":"https://github.com/qiao/PathFinding.js","keywords":["pathfinding","astar","dijkstra","game","algorithm","jumppoint","depthfirst","breadthfirst"],"author":"Xueqiao Xu ","main":"./index.js","dependencies":{"heap":"0.2.5"},"devDependencies":{"colors":"^1.0.3","del":"^0.1.3","gulp":"^3.8.10","gulp-browserify":"^0.5.0","gulp-concat":"^2.4.1","gulp-jshint":"^1.9.0","gulp-mocha":"^2.0.0","gulp-rename":"^1.2.0","gulp-uglify":"^1.0.1","inquirer":"^0.8.0","jshint-stylish":"^1.0.0","jsonfile":"^2.0.0","mocha":"2.0.x","semver":"^4.2.0","shelljs":"^0.3.0","should":"4.3.x"},"scripts":{"test":"gulp test"},"repository":{"type":"git","url":"git://github.com/qiao/PathFinding.js.git"},"licenses":[{"type":"MIT","url":"http://opensource.org/licenses/mit-license.php"}]} diff --git a/node_modules/pathfinding/src/PathFinding.js b/node_modules/pathfinding/src/PathFinding.js new file mode 100644 index 0000000..78e76bf --- /dev/null +++ b/node_modules/pathfinding/src/PathFinding.js @@ -0,0 +1,18 @@ +module.exports = { + 'Heap' : require('heap'), + 'Node' : require('./core/Node'), + 'Grid' : require('./core/Grid'), + 'Util' : require('./core/Util'), + 'DiagonalMovement' : require('./core/DiagonalMovement'), + 'Heuristic' : require('./core/Heuristic'), + 'AStarFinder' : require('./finders/AStarFinder'), + 'BestFirstFinder' : require('./finders/BestFirstFinder'), + 'BreadthFirstFinder' : require('./finders/BreadthFirstFinder'), + 'DijkstraFinder' : require('./finders/DijkstraFinder'), + 'BiAStarFinder' : require('./finders/BiAStarFinder'), + 'BiBestFirstFinder' : require('./finders/BiBestFirstFinder'), + 'BiBreadthFirstFinder' : require('./finders/BiBreadthFirstFinder'), + 'BiDijkstraFinder' : require('./finders/BiDijkstraFinder'), + 'IDAStarFinder' : require('./finders/IDAStarFinder'), + 'JumpPointFinder' : require('./finders/JumpPointFinder'), +}; diff --git a/node_modules/pathfinding/src/banner b/node_modules/pathfinding/src/banner new file mode 100644 index 0000000..62024b5 --- /dev/null +++ b/node_modules/pathfinding/src/banner @@ -0,0 +1,9 @@ +/** + * ____ _ _ _____ _ _ _ _ + * | _ \ __ _| |_| |__ | ___(_)_ __ __| (_)_ __ __ _ (_)___ + * | |_) / _` | __| '_ \| |_ | | '_ \ / _` | | '_ \ / _` | | / __| + * | __/ (_| | |_| | | | _| | | | | | (_| | | | | | (_| |_ | \__ \ + * |_| \__,_|\__|_| |_|_| |_|_| |_|\__,_|_|_| |_|\__, (_)/ |___/ + * |___/ |__/ + * https://github.com/qiao/PathFinding.js + */ diff --git a/node_modules/pathfinding/src/core/DiagonalMovement.js b/node_modules/pathfinding/src/core/DiagonalMovement.js new file mode 100644 index 0000000..5584773 --- /dev/null +++ b/node_modules/pathfinding/src/core/DiagonalMovement.js @@ -0,0 +1,8 @@ +var DiagonalMovement = { + Always: 1, + Never: 2, + IfAtMostOneObstacle: 3, + OnlyWhenNoObstacles: 4 +}; + +module.exports = DiagonalMovement; \ No newline at end of file diff --git a/node_modules/pathfinding/src/core/Grid.js b/node_modules/pathfinding/src/core/Grid.js new file mode 100644 index 0000000..19ba1f0 --- /dev/null +++ b/node_modules/pathfinding/src/core/Grid.js @@ -0,0 +1,245 @@ +var Node = require('./Node'); +var DiagonalMovement = require('./DiagonalMovement'); + +/** + * The Grid class, which serves as the encapsulation of the layout of the nodes. + * @constructor + * @param {number|Array>} width_or_matrix Number of columns of the grid, or matrix + * @param {number} height Number of rows of the grid. + * @param {Array>} [matrix] - A 0-1 matrix + * representing the walkable status of the nodes(0 or false for walkable). + * If the matrix is not supplied, all the nodes will be walkable. */ +function Grid(width_or_matrix, height, matrix) { + var width; + + if (typeof width_or_matrix !== 'object') { + width = width_or_matrix; + } else { + height = width_or_matrix.length; + width = width_or_matrix[0].length; + matrix = width_or_matrix; + } + + /** + * The number of columns of the grid. + * @type number + */ + this.width = width; + /** + * The number of rows of the grid. + * @type number + */ + this.height = height; + + /** + * A 2D array of nodes. + */ + this.nodes = this._buildNodes(width, height, matrix); +} + +/** + * Build and return the nodes. + * @private + * @param {number} width + * @param {number} height + * @param {Array>} [matrix] - A 0-1 matrix representing + * the walkable status of the nodes. + * @see Grid + */ +Grid.prototype._buildNodes = function(width, height, matrix) { + var i, j, + nodes = new Array(height); + + for (i = 0; i < height; ++i) { + nodes[i] = new Array(width); + for (j = 0; j < width; ++j) { + nodes[i][j] = new Node(j, i); + } + } + + + if (matrix === undefined) { + return nodes; + } + + if (matrix.length !== height || matrix[0].length !== width) { + throw new Error('Matrix size does not fit'); + } + + for (i = 0; i < height; ++i) { + for (j = 0; j < width; ++j) { + if (matrix[i][j]) { + // 0, false, null will be walkable + // while others will be un-walkable + nodes[i][j].walkable = false; + } + } + } + + return nodes; +}; + + +Grid.prototype.getNodeAt = function(x, y) { + return this.nodes[y][x]; +}; + + +/** + * Determine whether the node at the given position is walkable. + * (Also returns false if the position is outside the grid.) + * @param {number} x - The x coordinate of the node. + * @param {number} y - The y coordinate of the node. + * @return {boolean} - The walkability of the node. + */ +Grid.prototype.isWalkableAt = function(x, y) { + return this.isInside(x, y) && this.nodes[y][x].walkable; +}; + + +/** + * Determine whether the position is inside the grid. + * XXX: `grid.isInside(x, y)` is wierd to read. + * It should be `(x, y) is inside grid`, but I failed to find a better + * name for this method. + * @param {number} x + * @param {number} y + * @return {boolean} + */ +Grid.prototype.isInside = function(x, y) { + return (x >= 0 && x < this.width) && (y >= 0 && y < this.height); +}; + + +/** + * Set whether the node on the given position is walkable. + * NOTE: throws exception if the coordinate is not inside the grid. + * @param {number} x - The x coordinate of the node. + * @param {number} y - The y coordinate of the node. + * @param {boolean} walkable - Whether the position is walkable. + */ +Grid.prototype.setWalkableAt = function(x, y, walkable) { + this.nodes[y][x].walkable = walkable; +}; + + +/** + * Get the neighbors of the given node. + * + * offsets diagonalOffsets: + * +---+---+---+ +---+---+---+ + * | | 0 | | | 0 | | 1 | + * +---+---+---+ +---+---+---+ + * | 3 | | 1 | | | | | + * +---+---+---+ +---+---+---+ + * | | 2 | | | 3 | | 2 | + * +---+---+---+ +---+---+---+ + * + * When allowDiagonal is true, if offsets[i] is valid, then + * diagonalOffsets[i] and + * diagonalOffsets[(i + 1) % 4] is valid. + * @param {Node} node + * @param {DiagonalMovement} diagonalMovement + */ +Grid.prototype.getNeighbors = function(node, diagonalMovement) { + var x = node.x, + y = node.y, + neighbors = [], + s0 = false, d0 = false, + s1 = false, d1 = false, + s2 = false, d2 = false, + s3 = false, d3 = false, + nodes = this.nodes; + + // ↑ + if (this.isWalkableAt(x, y - 1)) { + neighbors.push(nodes[y - 1][x]); + s0 = true; + } + // → + if (this.isWalkableAt(x + 1, y)) { + neighbors.push(nodes[y][x + 1]); + s1 = true; + } + // ↓ + if (this.isWalkableAt(x, y + 1)) { + neighbors.push(nodes[y + 1][x]); + s2 = true; + } + // ← + if (this.isWalkableAt(x - 1, y)) { + neighbors.push(nodes[y][x - 1]); + s3 = true; + } + + if (diagonalMovement === DiagonalMovement.Never) { + return neighbors; + } + + if (diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { + d0 = s3 && s0; + d1 = s0 && s1; + d2 = s1 && s2; + d3 = s2 && s3; + } else if (diagonalMovement === DiagonalMovement.IfAtMostOneObstacle) { + d0 = s3 || s0; + d1 = s0 || s1; + d2 = s1 || s2; + d3 = s2 || s3; + } else if (diagonalMovement === DiagonalMovement.Always) { + d0 = true; + d1 = true; + d2 = true; + d3 = true; + } else { + throw new Error('Incorrect value of diagonalMovement'); + } + + // ↖ + if (d0 && this.isWalkableAt(x - 1, y - 1)) { + neighbors.push(nodes[y - 1][x - 1]); + } + // ↗ + if (d1 && this.isWalkableAt(x + 1, y - 1)) { + neighbors.push(nodes[y - 1][x + 1]); + } + // ↘ + if (d2 && this.isWalkableAt(x + 1, y + 1)) { + neighbors.push(nodes[y + 1][x + 1]); + } + // ↙ + if (d3 && this.isWalkableAt(x - 1, y + 1)) { + neighbors.push(nodes[y + 1][x - 1]); + } + + return neighbors; +}; + + +/** + * Get a clone of this grid. + * @return {Grid} Cloned grid. + */ +Grid.prototype.clone = function() { + var i, j, + + width = this.width, + height = this.height, + thisNodes = this.nodes, + + newGrid = new Grid(width, height), + newNodes = new Array(height); + + for (i = 0; i < height; ++i) { + newNodes[i] = new Array(width); + for (j = 0; j < width; ++j) { + newNodes[i][j] = new Node(j, i, thisNodes[i][j].walkable); + } + } + + newGrid.nodes = newNodes; + + return newGrid; +}; + +module.exports = Grid; diff --git a/node_modules/pathfinding/src/core/Heuristic.js b/node_modules/pathfinding/src/core/Heuristic.js new file mode 100644 index 0000000..30dfc1d --- /dev/null +++ b/node_modules/pathfinding/src/core/Heuristic.js @@ -0,0 +1,48 @@ +/** + * @namespace PF.Heuristic + * @description A collection of heuristic functions. + */ +module.exports = { + + /** + * Manhattan distance. + * @param {number} dx - Difference in x. + * @param {number} dy - Difference in y. + * @return {number} dx + dy + */ + manhattan: function(dx, dy) { + return dx + dy; + }, + + /** + * Euclidean distance. + * @param {number} dx - Difference in x. + * @param {number} dy - Difference in y. + * @return {number} sqrt(dx * dx + dy * dy) + */ + euclidean: function(dx, dy) { + return Math.sqrt(dx * dx + dy * dy); + }, + + /** + * Octile distance. + * @param {number} dx - Difference in x. + * @param {number} dy - Difference in y. + * @return {number} sqrt(dx * dx + dy * dy) for grids + */ + octile: function(dx, dy) { + var F = Math.SQRT2 - 1; + return (dx < dy) ? F * dx + dy : F * dy + dx; + }, + + /** + * Chebyshev distance. + * @param {number} dx - Difference in x. + * @param {number} dy - Difference in y. + * @return {number} max(dx, dy) + */ + chebyshev: function(dx, dy) { + return Math.max(dx, dy); + } + +}; diff --git a/node_modules/pathfinding/src/core/Node.js b/node_modules/pathfinding/src/core/Node.js new file mode 100644 index 0000000..2611fac --- /dev/null +++ b/node_modules/pathfinding/src/core/Node.js @@ -0,0 +1,28 @@ +/** + * A node in grid. + * This class holds some basic information about a node and custom + * attributes may be added, depending on the algorithms' needs. + * @constructor + * @param {number} x - The x coordinate of the node on the grid. + * @param {number} y - The y coordinate of the node on the grid. + * @param {boolean} [walkable] - Whether this node is walkable. + */ +function Node(x, y, walkable) { + /** + * The x coordinate of the node on the grid. + * @type number + */ + this.x = x; + /** + * The y coordinate of the node on the grid. + * @type number + */ + this.y = y; + /** + * Whether this node can be walked through. + * @type boolean + */ + this.walkable = (walkable === undefined ? true : walkable); +} + +module.exports = Node; diff --git a/node_modules/pathfinding/src/core/Util.js b/node_modules/pathfinding/src/core/Util.js new file mode 100644 index 0000000..ed7fd0f --- /dev/null +++ b/node_modules/pathfinding/src/core/Util.js @@ -0,0 +1,246 @@ +/** + * Backtrace according to the parent records and return the path. + * (including both start and end nodes) + * @param {Node} node End node + * @return {Array>} the path + */ +function backtrace(node) { + var path = [[node.x, node.y]]; + while (node.parent) { + node = node.parent; + path.push([node.x, node.y]); + } + return path.reverse(); +} +exports.backtrace = backtrace; + +/** + * Backtrace from start and end node, and return the path. + * (including both start and end nodes) + * @param {Node} + * @param {Node} + */ +function biBacktrace(nodeA, nodeB) { + var pathA = backtrace(nodeA), + pathB = backtrace(nodeB); + return pathA.concat(pathB.reverse()); +} +exports.biBacktrace = biBacktrace; + +/** + * Compute the length of the path. + * @param {Array>} path The path + * @return {number} The length of the path + */ +function pathLength(path) { + var i, sum = 0, a, b, dx, dy; + for (i = 1; i < path.length; ++i) { + a = path[i - 1]; + b = path[i]; + dx = a[0] - b[0]; + dy = a[1] - b[1]; + sum += Math.sqrt(dx * dx + dy * dy); + } + return sum; +} +exports.pathLength = pathLength; + + +/** + * Given the start and end coordinates, return all the coordinates lying + * on the line formed by these coordinates, based on Bresenham's algorithm. + * http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification + * @param {number} x0 Start x coordinate + * @param {number} y0 Start y coordinate + * @param {number} x1 End x coordinate + * @param {number} y1 End y coordinate + * @return {Array>} The coordinates on the line + */ +function interpolate(x0, y0, x1, y1) { + var abs = Math.abs, + line = [], + sx, sy, dx, dy, err, e2; + + dx = abs(x1 - x0); + dy = abs(y1 - y0); + + sx = (x0 < x1) ? 1 : -1; + sy = (y0 < y1) ? 1 : -1; + + err = dx - dy; + + while (true) { + line.push([x0, y0]); + + if (x0 === x1 && y0 === y1) { + break; + } + + e2 = 2 * err; + if (e2 > -dy) { + err = err - dy; + x0 = x0 + sx; + } + if (e2 < dx) { + err = err + dx; + y0 = y0 + sy; + } + } + + return line; +} +exports.interpolate = interpolate; + + +/** + * Given a compressed path, return a new path that has all the segments + * in it interpolated. + * @param {Array>} path The path + * @return {Array>} expanded path + */ +function expandPath(path) { + var expanded = [], + len = path.length, + coord0, coord1, + interpolated, + interpolatedLen, + i, j; + + if (len < 2) { + return expanded; + } + + for (i = 0; i < len - 1; ++i) { + coord0 = path[i]; + coord1 = path[i + 1]; + + interpolated = interpolate(coord0[0], coord0[1], coord1[0], coord1[1]); + interpolatedLen = interpolated.length; + for (j = 0; j < interpolatedLen - 1; ++j) { + expanded.push(interpolated[j]); + } + } + expanded.push(path[len - 1]); + + return expanded; +} +exports.expandPath = expandPath; + + +/** + * Smoothen the give path. + * The original path will not be modified; a new path will be returned. + * @param {PF.Grid} grid + * @param {Array>} path The path + */ +function smoothenPath(grid, path) { + var len = path.length, + x0 = path[0][0], // path start x + y0 = path[0][1], // path start y + x1 = path[len - 1][0], // path end x + y1 = path[len - 1][1], // path end y + sx, sy, // current start coordinate + ex, ey, // current end coordinate + newPath, + i, j, coord, line, testCoord, blocked; + + sx = x0; + sy = y0; + newPath = [[sx, sy]]; + + for (i = 2; i < len; ++i) { + coord = path[i]; + ex = coord[0]; + ey = coord[1]; + line = interpolate(sx, sy, ex, ey); + + blocked = false; + for (j = 1; j < line.length; ++j) { + testCoord = line[j]; + + if (!grid.isWalkableAt(testCoord[0], testCoord[1])) { + blocked = true; + break; + } + } + if (blocked) { + lastValidCoord = path[i - 1]; + newPath.push(lastValidCoord); + sx = lastValidCoord[0]; + sy = lastValidCoord[1]; + } + } + newPath.push([x1, y1]); + + return newPath; +} +exports.smoothenPath = smoothenPath; + + +/** + * Compress a path, remove redundant nodes without altering the shape + * The original path is not modified + * @param {Array>} path The path + * @return {Array>} The compressed path + */ +function compressPath(path) { + + // nothing to compress + if(path.length < 3) { + return path; + } + + var compressed = [], + sx = path[0][0], // start x + sy = path[0][1], // start y + px = path[1][0], // second point x + py = path[1][1], // second point y + dx = px - sx, // direction between the two points + dy = py - sy, // direction between the two points + lx, ly, + ldx, ldy, + sq, i; + + // normalize the direction + sq = Math.sqrt(dx*dx + dy*dy); + dx /= sq; + dy /= sq; + + // start the new path + compressed.push([sx,sy]); + + for(i = 2; i < path.length; i++) { + + // store the last point + lx = px; + ly = py; + + // store the last direction + ldx = dx; + ldy = dy; + + // next point + px = path[i][0]; + py = path[i][1]; + + // next direction + dx = px - lx; + dy = py - ly; + + // normalize + sq = Math.sqrt(dx*dx + dy*dy); + dx /= sq; + dy /= sq; + + // if the direction has changed, store the point + if ( dx !== ldx || dy !== ldy ) { + compressed.push([lx,ly]); + } + } + + // store the last point + compressed.push([px,py]); + + return compressed; +} +exports.compressPath = compressPath; diff --git a/node_modules/pathfinding/src/finders/AStarFinder.js b/node_modules/pathfinding/src/finders/AStarFinder.js new file mode 100644 index 0000000..e9b2c42 --- /dev/null +++ b/node_modules/pathfinding/src/finders/AStarFinder.js @@ -0,0 +1,126 @@ +var Heap = require('heap'); +var Util = require('../core/Util'); +var Heuristic = require('../core/Heuristic'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * A* path-finder. Based upon https://github.com/bgrins/javascript-astar + * @constructor + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + * @param {number} opt.weight Weight to apply to the heuristic to allow for + * suboptimal paths, in order to speed up the search. + */ +function AStarFinder(opt) { + opt = opt || {}; + this.allowDiagonal = opt.allowDiagonal; + this.dontCrossCorners = opt.dontCrossCorners; + this.heuristic = opt.heuristic || Heuristic.manhattan; + this.weight = opt.weight || 1; + this.diagonalMovement = opt.diagonalMovement; + + if (!this.diagonalMovement) { + if (!this.allowDiagonal) { + this.diagonalMovement = DiagonalMovement.Never; + } else { + if (this.dontCrossCorners) { + this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; + } else { + this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; + } + } + } + + // When diagonal movement is allowed the manhattan heuristic is not + //admissible. It should be octile instead + if (this.diagonalMovement === DiagonalMovement.Never) { + this.heuristic = opt.heuristic || Heuristic.manhattan; + } else { + this.heuristic = opt.heuristic || Heuristic.octile; + } +} + +/** + * Find and return the the path. + * @return {Array>} The path, including both start and + * end positions. + */ +AStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { + var openList = new Heap(function(nodeA, nodeB) { + return nodeA.f - nodeB.f; + }), + startNode = grid.getNodeAt(startX, startY), + endNode = grid.getNodeAt(endX, endY), + heuristic = this.heuristic, + diagonalMovement = this.diagonalMovement, + weight = this.weight, + abs = Math.abs, SQRT2 = Math.SQRT2, + node, neighbors, neighbor, i, l, x, y, ng; + + // set the `g` and `f` value of the start node to be 0 + startNode.g = 0; + startNode.f = 0; + + // push the start node into the open list + openList.push(startNode); + startNode.opened = true; + + // while the open list is not empty + while (!openList.empty()) { + // pop the position of node which has the minimum `f` value. + node = openList.pop(); + node.closed = true; + + // if reached the end position, construct the path and return it + if (node === endNode) { + return Util.backtrace(endNode); + } + + // get neigbours of the current node + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + if (neighbor.closed) { + continue; + } + + x = neighbor.x; + y = neighbor.y; + + // get the distance between current node and the neighbor + // and calculate the next g score + ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); + + // check if the neighbor has not been inspected yet, or + // can be reached with smaller cost from the current node + if (!neighbor.opened || ng < neighbor.g) { + neighbor.g = ng; + neighbor.h = neighbor.h || weight * heuristic(abs(x - endX), abs(y - endY)); + neighbor.f = neighbor.g + neighbor.h; + neighbor.parent = node; + + if (!neighbor.opened) { + openList.push(neighbor); + neighbor.opened = true; + } else { + // the neighbor can be reached with smaller cost. + // Since its f value has been updated, we have to + // update its position in the open list + openList.updateItem(neighbor); + } + } + } // end for each neighbor + } // end while not open list empty + + // fail to find the path + return []; +}; + +module.exports = AStarFinder; diff --git a/node_modules/pathfinding/src/finders/BestFirstFinder.js b/node_modules/pathfinding/src/finders/BestFirstFinder.js new file mode 100644 index 0000000..d6b1dc8 --- /dev/null +++ b/node_modules/pathfinding/src/finders/BestFirstFinder.js @@ -0,0 +1,28 @@ +var AStarFinder = require('./AStarFinder'); + +/** + * Best-First-Search path-finder. + * @constructor + * @extends AStarFinder + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + */ +function BestFirstFinder(opt) { + AStarFinder.call(this, opt); + + var orig = this.heuristic; + this.heuristic = function(dx, dy) { + return orig(dx, dy) * 1000000; + }; +} + +BestFirstFinder.prototype = new AStarFinder(); +BestFirstFinder.prototype.constructor = BestFirstFinder; + +module.exports = BestFirstFinder; diff --git a/node_modules/pathfinding/src/finders/BiAStarFinder.js b/node_modules/pathfinding/src/finders/BiAStarFinder.js new file mode 100644 index 0000000..c20e22c --- /dev/null +++ b/node_modules/pathfinding/src/finders/BiAStarFinder.js @@ -0,0 +1,181 @@ +var Heap = require('heap'); +var Util = require('../core/Util'); +var Heuristic = require('../core/Heuristic'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * A* path-finder. + * based upon https://github.com/bgrins/javascript-astar + * @constructor + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + * @param {number} opt.weight Weight to apply to the heuristic to allow for + * suboptimal paths, in order to speed up the search. + */ +function BiAStarFinder(opt) { + opt = opt || {}; + this.allowDiagonal = opt.allowDiagonal; + this.dontCrossCorners = opt.dontCrossCorners; + this.diagonalMovement = opt.diagonalMovement; + this.heuristic = opt.heuristic || Heuristic.manhattan; + this.weight = opt.weight || 1; + + if (!this.diagonalMovement) { + if (!this.allowDiagonal) { + this.diagonalMovement = DiagonalMovement.Never; + } else { + if (this.dontCrossCorners) { + this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; + } else { + this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; + } + } + } + + //When diagonal movement is allowed the manhattan heuristic is not admissible + //It should be octile instead + if (this.diagonalMovement === DiagonalMovement.Never) { + this.heuristic = opt.heuristic || Heuristic.manhattan; + } else { + this.heuristic = opt.heuristic || Heuristic.octile; + } +} + +/** + * Find and return the the path. + * @return {Array>} The path, including both start and + * end positions. + */ +BiAStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { + var cmp = function(nodeA, nodeB) { + return nodeA.f - nodeB.f; + }, + startOpenList = new Heap(cmp), + endOpenList = new Heap(cmp), + startNode = grid.getNodeAt(startX, startY), + endNode = grid.getNodeAt(endX, endY), + heuristic = this.heuristic, + diagonalMovement = this.diagonalMovement, + weight = this.weight, + abs = Math.abs, SQRT2 = Math.SQRT2, + node, neighbors, neighbor, i, l, x, y, ng, + BY_START = 1, BY_END = 2; + + // set the `g` and `f` value of the start node to be 0 + // and push it into the start open list + startNode.g = 0; + startNode.f = 0; + startOpenList.push(startNode); + startNode.opened = BY_START; + + // set the `g` and `f` value of the end node to be 0 + // and push it into the open open list + endNode.g = 0; + endNode.f = 0; + endOpenList.push(endNode); + endNode.opened = BY_END; + + // while both the open lists are not empty + while (!startOpenList.empty() && !endOpenList.empty()) { + + // pop the position of start node which has the minimum `f` value. + node = startOpenList.pop(); + node.closed = true; + + // get neigbours of the current node + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + if (neighbor.closed) { + continue; + } + if (neighbor.opened === BY_END) { + return Util.biBacktrace(node, neighbor); + } + + x = neighbor.x; + y = neighbor.y; + + // get the distance between current node and the neighbor + // and calculate the next g score + ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); + + // check if the neighbor has not been inspected yet, or + // can be reached with smaller cost from the current node + if (!neighbor.opened || ng < neighbor.g) { + neighbor.g = ng; + neighbor.h = neighbor.h || + weight * heuristic(abs(x - endX), abs(y - endY)); + neighbor.f = neighbor.g + neighbor.h; + neighbor.parent = node; + + if (!neighbor.opened) { + startOpenList.push(neighbor); + neighbor.opened = BY_START; + } else { + // the neighbor can be reached with smaller cost. + // Since its f value has been updated, we have to + // update its position in the open list + startOpenList.updateItem(neighbor); + } + } + } // end for each neighbor + + + // pop the position of end node which has the minimum `f` value. + node = endOpenList.pop(); + node.closed = true; + + // get neigbours of the current node + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + if (neighbor.closed) { + continue; + } + if (neighbor.opened === BY_START) { + return Util.biBacktrace(neighbor, node); + } + + x = neighbor.x; + y = neighbor.y; + + // get the distance between current node and the neighbor + // and calculate the next g score + ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); + + // check if the neighbor has not been inspected yet, or + // can be reached with smaller cost from the current node + if (!neighbor.opened || ng < neighbor.g) { + neighbor.g = ng; + neighbor.h = neighbor.h || + weight * heuristic(abs(x - startX), abs(y - startY)); + neighbor.f = neighbor.g + neighbor.h; + neighbor.parent = node; + + if (!neighbor.opened) { + endOpenList.push(neighbor); + neighbor.opened = BY_END; + } else { + // the neighbor can be reached with smaller cost. + // Since its f value has been updated, we have to + // update its position in the open list + endOpenList.updateItem(neighbor); + } + } + } // end for each neighbor + } // end while not open list empty + + // fail to find the path + return []; +}; + +module.exports = BiAStarFinder; diff --git a/node_modules/pathfinding/src/finders/BiBestFirstFinder.js b/node_modules/pathfinding/src/finders/BiBestFirstFinder.js new file mode 100644 index 0000000..a90de48 --- /dev/null +++ b/node_modules/pathfinding/src/finders/BiBestFirstFinder.js @@ -0,0 +1,28 @@ +var BiAStarFinder = require('./BiAStarFinder'); + +/** + * Bi-direcitional Best-First-Search path-finder. + * @constructor + * @extends BiAStarFinder + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + */ +function BiBestFirstFinder(opt) { + BiAStarFinder.call(this, opt); + + var orig = this.heuristic; + this.heuristic = function(dx, dy) { + return orig(dx, dy) * 1000000; + }; +} + +BiBestFirstFinder.prototype = new BiAStarFinder(); +BiBestFirstFinder.prototype.constructor = BiBestFirstFinder; + +module.exports = BiBestFirstFinder; diff --git a/node_modules/pathfinding/src/finders/BiBreadthFirstFinder.js b/node_modules/pathfinding/src/finders/BiBreadthFirstFinder.js new file mode 100644 index 0000000..1238e98 --- /dev/null +++ b/node_modules/pathfinding/src/finders/BiBreadthFirstFinder.js @@ -0,0 +1,115 @@ +var Util = require('../core/Util'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Bi-directional Breadth-First-Search path finder. + * @constructor + * @param {object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + */ +function BiBreadthFirstFinder(opt) { + opt = opt || {}; + this.allowDiagonal = opt.allowDiagonal; + this.dontCrossCorners = opt.dontCrossCorners; + this.diagonalMovement = opt.diagonalMovement; + + if (!this.diagonalMovement) { + if (!this.allowDiagonal) { + this.diagonalMovement = DiagonalMovement.Never; + } else { + if (this.dontCrossCorners) { + this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; + } else { + this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; + } + } + } +} + + +/** + * Find and return the the path. + * @return {Array>} The path, including both start and + * end positions. + */ +BiBreadthFirstFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { + var startNode = grid.getNodeAt(startX, startY), + endNode = grid.getNodeAt(endX, endY), + startOpenList = [], endOpenList = [], + neighbors, neighbor, node, + diagonalMovement = this.diagonalMovement, + BY_START = 0, BY_END = 1, + i, l; + + // push the start and end nodes into the queues + startOpenList.push(startNode); + startNode.opened = true; + startNode.by = BY_START; + + endOpenList.push(endNode); + endNode.opened = true; + endNode.by = BY_END; + + // while both the queues are not empty + while (startOpenList.length && endOpenList.length) { + + // expand start open list + + node = startOpenList.shift(); + node.closed = true; + + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + if (neighbor.closed) { + continue; + } + if (neighbor.opened) { + // if this node has been inspected by the reversed search, + // then a path is found. + if (neighbor.by === BY_END) { + return Util.biBacktrace(node, neighbor); + } + continue; + } + startOpenList.push(neighbor); + neighbor.parent = node; + neighbor.opened = true; + neighbor.by = BY_START; + } + + // expand end open list + + node = endOpenList.shift(); + node.closed = true; + + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + if (neighbor.closed) { + continue; + } + if (neighbor.opened) { + if (neighbor.by === BY_START) { + return Util.biBacktrace(neighbor, node); + } + continue; + } + endOpenList.push(neighbor); + neighbor.parent = node; + neighbor.opened = true; + neighbor.by = BY_END; + } + } + + // fail to find the path + return []; +}; + +module.exports = BiBreadthFirstFinder; diff --git a/node_modules/pathfinding/src/finders/BiDijkstraFinder.js b/node_modules/pathfinding/src/finders/BiDijkstraFinder.js new file mode 100644 index 0000000..5e5017e --- /dev/null +++ b/node_modules/pathfinding/src/finders/BiDijkstraFinder.js @@ -0,0 +1,24 @@ +var BiAStarFinder = require('./BiAStarFinder'); + +/** + * Bi-directional Dijkstra path-finder. + * @constructor + * @extends BiAStarFinder + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + */ +function BiDijkstraFinder(opt) { + BiAStarFinder.call(this, opt); + this.heuristic = function(dx, dy) { + return 0; + }; +} + +BiDijkstraFinder.prototype = new BiAStarFinder(); +BiDijkstraFinder.prototype.constructor = BiDijkstraFinder; + +module.exports = BiDijkstraFinder; diff --git a/node_modules/pathfinding/src/finders/BreadthFirstFinder.js b/node_modules/pathfinding/src/finders/BreadthFirstFinder.js new file mode 100644 index 0000000..837a414 --- /dev/null +++ b/node_modules/pathfinding/src/finders/BreadthFirstFinder.js @@ -0,0 +1,79 @@ +var Util = require('../core/Util'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Breadth-First-Search path finder. + * @constructor + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + */ +function BreadthFirstFinder(opt) { + opt = opt || {}; + this.allowDiagonal = opt.allowDiagonal; + this.dontCrossCorners = opt.dontCrossCorners; + this.diagonalMovement = opt.diagonalMovement; + + if (!this.diagonalMovement) { + if (!this.allowDiagonal) { + this.diagonalMovement = DiagonalMovement.Never; + } else { + if (this.dontCrossCorners) { + this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; + } else { + this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; + } + } + } +} + +/** + * Find and return the the path. + * @return {Array>} The path, including both start and + * end positions. + */ +BreadthFirstFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { + var openList = [], + diagonalMovement = this.diagonalMovement, + startNode = grid.getNodeAt(startX, startY), + endNode = grid.getNodeAt(endX, endY), + neighbors, neighbor, node, i, l; + + // push the start pos into the queue + openList.push(startNode); + startNode.opened = true; + + // while the queue is not empty + while (openList.length) { + // take the front node from the queue + node = openList.shift(); + node.closed = true; + + // reached the end position + if (node === endNode) { + return Util.backtrace(endNode); + } + + neighbors = grid.getNeighbors(node, diagonalMovement); + for (i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + + // skip this neighbor if it has been inspected before + if (neighbor.closed || neighbor.opened) { + continue; + } + + openList.push(neighbor); + neighbor.opened = true; + neighbor.parent = node; + } + } + + // fail to find the path + return []; +}; + +module.exports = BreadthFirstFinder; diff --git a/node_modules/pathfinding/src/finders/DijkstraFinder.js b/node_modules/pathfinding/src/finders/DijkstraFinder.js new file mode 100644 index 0000000..9b3a284 --- /dev/null +++ b/node_modules/pathfinding/src/finders/DijkstraFinder.js @@ -0,0 +1,24 @@ +var AStarFinder = require('./AStarFinder'); + +/** + * Dijkstra path-finder. + * @constructor + * @extends AStarFinder + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + */ +function DijkstraFinder(opt) { + AStarFinder.call(this, opt); + this.heuristic = function(dx, dy) { + return 0; + }; +} + +DijkstraFinder.prototype = new AStarFinder(); +DijkstraFinder.prototype.constructor = DijkstraFinder; + +module.exports = DijkstraFinder; diff --git a/node_modules/pathfinding/src/finders/IDAStarFinder.js b/node_modules/pathfinding/src/finders/IDAStarFinder.js new file mode 100644 index 0000000..71508ae --- /dev/null +++ b/node_modules/pathfinding/src/finders/IDAStarFinder.js @@ -0,0 +1,209 @@ +var Util = require('../core/Util'); +var Heuristic = require('../core/Heuristic'); +var Node = require('../core/Node'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Iterative Deeping A Star (IDA*) path-finder. + * + * Recursion based on: + * http://www.apl.jhu.edu/~hall/AI-Programming/IDA-Star.html + * + * Path retracing based on: + * V. Nageshwara Rao, Vipin Kumar and K. Ramesh + * "A Parallel Implementation of Iterative-Deeping-A*", January 1987. + * ftp://ftp.cs.utexas.edu/.snapshot/hourly.1/pub/AI-Lab/tech-reports/UT-AI-TR-87-46.pdf + * + * @author Gerard Meier (www.gerardmeier.com) + * + * @constructor + * @param {Object} opt + * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. + * Deprecated, use diagonalMovement instead. + * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching + * block corners. Deprecated, use diagonalMovement instead. + * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + * @param {number} opt.weight Weight to apply to the heuristic to allow for + * suboptimal paths, in order to speed up the search. + * @param {boolean} opt.trackRecursion Whether to track recursion for + * statistical purposes. + * @param {number} opt.timeLimit Maximum execution time. Use <= 0 for infinite. + */ +function IDAStarFinder(opt) { + opt = opt || {}; + this.allowDiagonal = opt.allowDiagonal; + this.dontCrossCorners = opt.dontCrossCorners; + this.diagonalMovement = opt.diagonalMovement; + this.heuristic = opt.heuristic || Heuristic.manhattan; + this.weight = opt.weight || 1; + this.trackRecursion = opt.trackRecursion || false; + this.timeLimit = opt.timeLimit || Infinity; // Default: no time limit. + + if (!this.diagonalMovement) { + if (!this.allowDiagonal) { + this.diagonalMovement = DiagonalMovement.Never; + } else { + if (this.dontCrossCorners) { + this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; + } else { + this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; + } + } + } + + // When diagonal movement is allowed the manhattan heuristic is not + // admissible, it should be octile instead + if (this.diagonalMovement === DiagonalMovement.Never) { + this.heuristic = opt.heuristic || Heuristic.manhattan; + } else { + this.heuristic = opt.heuristic || Heuristic.octile; + } +} + +/** + * Find and return the the path. When an empty array is returned, either + * no path is possible, or the maximum execution time is reached. + * + * @return {Array>} The path, including both start and + * end positions. + */ +IDAStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { + // Used for statistics: + var nodesVisited = 0; + + // Execution time limitation: + var startTime = new Date().getTime(); + + // Heuristic helper: + var h = function(a, b) { + return this.heuristic(Math.abs(b.x - a.x), Math.abs(b.y - a.y)); + }.bind(this); + + // Step cost from a to b: + var cost = function(a, b) { + return (a.x === b.x || a.y === b.y) ? 1 : Math.SQRT2; + }; + + /** + * IDA* search implementation. + * + * @param {Node} The node currently expanding from. + * @param {number} Cost to reach the given node. + * @param {number} Maximum search depth (cut-off value). + * @param {Array>} The found route. + * @param {number} Recursion depth. + * + * @return {Object} either a number with the new optimal cut-off depth, + * or a valid node instance, in which case a path was found. + */ + var search = function(node, g, cutoff, route, depth) { + nodesVisited++; + + // Enforce timelimit: + if (this.timeLimit > 0 && + new Date().getTime() - startTime > this.timeLimit * 1000) { + // Enforced as "path-not-found". + return Infinity; + } + + var f = g + h(node, end) * this.weight; + + // We've searched too deep for this iteration. + if (f > cutoff) { + return f; + } + + if (node == end) { + route[depth] = [node.x, node.y]; + return node; + } + + var min, t, k, neighbour; + + var neighbours = grid.getNeighbors(node, this.diagonalMovement); + + // Sort the neighbours, gives nicer paths. But, this deviates + // from the original algorithm - so I left it out. + //neighbours.sort(function(a, b){ + // return h(a, end) - h(b, end); + //}); + + + /*jshint -W084 *///Disable warning: Expected a conditional expression and instead saw an assignment + for (k = 0, min = Infinity; neighbour = neighbours[k]; ++k) { + /*jshint +W084 *///Enable warning: Expected a conditional expression and instead saw an assignment + if (this.trackRecursion) { + // Retain a copy for visualisation. Due to recursion, this + // node may be part of other paths too. + neighbour.retainCount = neighbour.retainCount + 1 || 1; + + if(neighbour.tested !== true) { + neighbour.tested = true; + } + } + + t = search(neighbour, g + cost(node, neighbour), cutoff, route, depth + 1); + + if (t instanceof Node) { + route[depth] = [node.x, node.y]; + + // For a typical A* linked list, this would work: + // neighbour.parent = node; + return t; + } + + // Decrement count, then determine whether it's actually closed. + if (this.trackRecursion && (--neighbour.retainCount) === 0) { + neighbour.tested = false; + } + + if (t < min) { + min = t; + } + } + + return min; + + }.bind(this); + + // Node instance lookups: + var start = grid.getNodeAt(startX, startY); + var end = grid.getNodeAt(endX, endY); + + // Initial search depth, given the typical heuristic contraints, + // there should be no cheaper route possible. + var cutOff = h(start, end); + + var j, route, t; + + // With an overflow protection. + for (j = 0; true; ++j) { + + route = []; + + // Search till cut-off depth: + t = search(start, 0, cutOff, route, 0); + + // Route not possible, or not found in time limit. + if (t === Infinity) { + return []; + } + + // If t is a node, it's also the end node. Route is now + // populated with a valid path to the end node. + if (t instanceof Node) { + return route; + } + + // Try again, this time with a deeper cut-off. The t score + // is the closest we got to the end node. + cutOff = t; + } + + // This _should_ never to be reached. + return []; +}; + +module.exports = IDAStarFinder; diff --git a/node_modules/pathfinding/src/finders/JPFAlwaysMoveDiagonally.js b/node_modules/pathfinding/src/finders/JPFAlwaysMoveDiagonally.js new file mode 100644 index 0000000..06bfd0a --- /dev/null +++ b/node_modules/pathfinding/src/finders/JPFAlwaysMoveDiagonally.js @@ -0,0 +1,149 @@ +/** + * @author imor / https://github.com/imor + */ +var JumpPointFinderBase = require('./JumpPointFinderBase'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Path finder using the Jump Point Search algorithm which always moves + * diagonally irrespective of the number of obstacles. + */ +function JPFAlwaysMoveDiagonally(opt) { + JumpPointFinderBase.call(this, opt); +} + +JPFAlwaysMoveDiagonally.prototype = new JumpPointFinderBase(); +JPFAlwaysMoveDiagonally.prototype.constructor = JPFAlwaysMoveDiagonally; + +/** + * Search recursively in the direction (parent -> child), stopping only when a + * jump point is found. + * @protected + * @return {Array>} The x, y coordinate of the jump point + * found, or null if not found + */ +JPFAlwaysMoveDiagonally.prototype._jump = function(x, y, px, py) { + var grid = this.grid, + dx = x - px, dy = y - py; + + if (!grid.isWalkableAt(x, y)) { + return null; + } + + if(this.trackJumpRecursion === true) { + grid.getNodeAt(x, y).tested = true; + } + + if (grid.getNodeAt(x, y) === this.endNode) { + return [x, y]; + } + + // check for forced neighbors + // along the diagonal + if (dx !== 0 && dy !== 0) { + if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || + (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { + return [x, y]; + } + // when moving diagonally, must check for vertical/horizontal jump points + if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { + return [x, y]; + } + } + // horizontally/vertically + else { + if( dx !== 0 ) { // moving along x + if((grid.isWalkableAt(x + dx, y + 1) && !grid.isWalkableAt(x, y + 1)) || + (grid.isWalkableAt(x + dx, y - 1) && !grid.isWalkableAt(x, y - 1))) { + return [x, y]; + } + } + else { + if((grid.isWalkableAt(x + 1, y + dy) && !grid.isWalkableAt(x + 1, y)) || + (grid.isWalkableAt(x - 1, y + dy) && !grid.isWalkableAt(x - 1, y))) { + return [x, y]; + } + } + } + + return this._jump(x + dx, y + dy, x, y); +}; + +/** + * Find the neighbors for the given node. If the node has a parent, + * prune the neighbors based on the jump point search algorithm, otherwise + * return all available neighbors. + * @return {Array>} The neighbors found. + */ +JPFAlwaysMoveDiagonally.prototype._findNeighbors = function(node) { + var parent = node.parent, + x = node.x, y = node.y, + grid = this.grid, + px, py, nx, ny, dx, dy, + neighbors = [], neighborNodes, neighborNode, i, l; + + // directed pruning: can ignore most neighbors, unless forced. + if (parent) { + px = parent.x; + py = parent.y; + // get the normalized direction of travel + dx = (x - px) / Math.max(Math.abs(x - px), 1); + dy = (y - py) / Math.max(Math.abs(y - py), 1); + + // search diagonally + if (dx !== 0 && dy !== 0) { + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + } + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + } + if (grid.isWalkableAt(x + dx, y + dy)) { + neighbors.push([x + dx, y + dy]); + } + if (!grid.isWalkableAt(x - dx, y)) { + neighbors.push([x - dx, y + dy]); + } + if (!grid.isWalkableAt(x, y - dy)) { + neighbors.push([x + dx, y - dy]); + } + } + // search horizontally/vertically + else { + if(dx === 0) { + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + } + if (!grid.isWalkableAt(x + 1, y)) { + neighbors.push([x + 1, y + dy]); + } + if (!grid.isWalkableAt(x - 1, y)) { + neighbors.push([x - 1, y + dy]); + } + } + else { + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + } + if (!grid.isWalkableAt(x, y + 1)) { + neighbors.push([x + dx, y + 1]); + } + if (!grid.isWalkableAt(x, y - 1)) { + neighbors.push([x + dx, y - 1]); + } + } + } + } + // return all neighbors + else { + neighborNodes = grid.getNeighbors(node, DiagonalMovement.Always); + for (i = 0, l = neighborNodes.length; i < l; ++i) { + neighborNode = neighborNodes[i]; + neighbors.push([neighborNode.x, neighborNode.y]); + } + } + + return neighbors; +}; + +module.exports = JPFAlwaysMoveDiagonally; diff --git a/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfAtMostOneObstacle.js b/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfAtMostOneObstacle.js new file mode 100644 index 0000000..d50ec42 --- /dev/null +++ b/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfAtMostOneObstacle.js @@ -0,0 +1,155 @@ +/** + * @author imor / https://github.com/imor + */ +var JumpPointFinderBase = require('./JumpPointFinderBase'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Path finder using the Jump Point Search algorithm which moves + * diagonally only when there is at most one obstacle. + */ +function JPFMoveDiagonallyIfAtMostOneObstacle(opt) { + JumpPointFinderBase.call(this, opt); +} + +JPFMoveDiagonallyIfAtMostOneObstacle.prototype = new JumpPointFinderBase(); +JPFMoveDiagonallyIfAtMostOneObstacle.prototype.constructor = JPFMoveDiagonallyIfAtMostOneObstacle; + +/** + * Search recursively in the direction (parent -> child), stopping only when a + * jump point is found. + * @protected + * @return {Array>} The x, y coordinate of the jump point + * found, or null if not found + */ +JPFMoveDiagonallyIfAtMostOneObstacle.prototype._jump = function(x, y, px, py) { + var grid = this.grid, + dx = x - px, dy = y - py; + + if (!grid.isWalkableAt(x, y)) { + return null; + } + + if(this.trackJumpRecursion === true) { + grid.getNodeAt(x, y).tested = true; + } + + if (grid.getNodeAt(x, y) === this.endNode) { + return [x, y]; + } + + // check for forced neighbors + // along the diagonal + if (dx !== 0 && dy !== 0) { + if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || + (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { + return [x, y]; + } + // when moving diagonally, must check for vertical/horizontal jump points + if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { + return [x, y]; + } + } + // horizontally/vertically + else { + if( dx !== 0 ) { // moving along x + if((grid.isWalkableAt(x + dx, y + 1) && !grid.isWalkableAt(x, y + 1)) || + (grid.isWalkableAt(x + dx, y - 1) && !grid.isWalkableAt(x, y - 1))) { + return [x, y]; + } + } + else { + if((grid.isWalkableAt(x + 1, y + dy) && !grid.isWalkableAt(x + 1, y)) || + (grid.isWalkableAt(x - 1, y + dy) && !grid.isWalkableAt(x - 1, y))) { + return [x, y]; + } + } + } + + // moving diagonally, must make sure one of the vertical/horizontal + // neighbors is open to allow the path + if (grid.isWalkableAt(x + dx, y) || grid.isWalkableAt(x, y + dy)) { + return this._jump(x + dx, y + dy, x, y); + } else { + return null; + } +}; + +/** + * Find the neighbors for the given node. If the node has a parent, + * prune the neighbors based on the jump point search algorithm, otherwise + * return all available neighbors. + * @return {Array>} The neighbors found. + */ +JPFMoveDiagonallyIfAtMostOneObstacle.prototype._findNeighbors = function(node) { + var parent = node.parent, + x = node.x, y = node.y, + grid = this.grid, + px, py, nx, ny, dx, dy, + neighbors = [], neighborNodes, neighborNode, i, l; + + // directed pruning: can ignore most neighbors, unless forced. + if (parent) { + px = parent.x; + py = parent.y; + // get the normalized direction of travel + dx = (x - px) / Math.max(Math.abs(x - px), 1); + dy = (y - py) / Math.max(Math.abs(y - py), 1); + + // search diagonally + if (dx !== 0 && dy !== 0) { + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + } + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + } + if (grid.isWalkableAt(x, y + dy) || grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y + dy]); + } + if (!grid.isWalkableAt(x - dx, y) && grid.isWalkableAt(x, y + dy)) { + neighbors.push([x - dx, y + dy]); + } + if (!grid.isWalkableAt(x, y - dy) && grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y - dy]); + } + } + // search horizontally/vertically + else { + if(dx === 0) { + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + if (!grid.isWalkableAt(x + 1, y)) { + neighbors.push([x + 1, y + dy]); + } + if (!grid.isWalkableAt(x - 1, y)) { + neighbors.push([x - 1, y + dy]); + } + } + } + else { + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + if (!grid.isWalkableAt(x, y + 1)) { + neighbors.push([x + dx, y + 1]); + } + if (!grid.isWalkableAt(x, y - 1)) { + neighbors.push([x + dx, y - 1]); + } + } + } + } + } + // return all neighbors + else { + neighborNodes = grid.getNeighbors(node, DiagonalMovement.IfAtMostOneObstacle); + for (i = 0, l = neighborNodes.length; i < l; ++i) { + neighborNode = neighborNodes[i]; + neighbors.push([neighborNode.x, neighborNode.y]); + } + } + + return neighbors; +}; + +module.exports = JPFMoveDiagonallyIfAtMostOneObstacle; diff --git a/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfNoObstacles.js b/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfNoObstacles.js new file mode 100644 index 0000000..fcec204 --- /dev/null +++ b/node_modules/pathfinding/src/finders/JPFMoveDiagonallyIfNoObstacles.js @@ -0,0 +1,174 @@ +/** + * @author imor / https://github.com/imor + */ +var JumpPointFinderBase = require('./JumpPointFinderBase'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Path finder using the Jump Point Search algorithm which moves + * diagonally only when there are no obstacles. + */ +function JPFMoveDiagonallyIfNoObstacles(opt) { + JumpPointFinderBase.call(this, opt); +} + +JPFMoveDiagonallyIfNoObstacles.prototype = new JumpPointFinderBase(); +JPFMoveDiagonallyIfNoObstacles.prototype.constructor = JPFMoveDiagonallyIfNoObstacles; + +/** + * Search recursively in the direction (parent -> child), stopping only when a + * jump point is found. + * @protected + * @return {Array>} The x, y coordinate of the jump point + * found, or null if not found + */ +JPFMoveDiagonallyIfNoObstacles.prototype._jump = function(x, y, px, py) { + var grid = this.grid, + dx = x - px, dy = y - py; + + if (!grid.isWalkableAt(x, y)) { + return null; + } + + if(this.trackJumpRecursion === true) { + grid.getNodeAt(x, y).tested = true; + } + + if (grid.getNodeAt(x, y) === this.endNode) { + return [x, y]; + } + + // check for forced neighbors + // along the diagonal + if (dx !== 0 && dy !== 0) { + // if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || + // (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { + // return [x, y]; + // } + // when moving diagonally, must check for vertical/horizontal jump points + if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { + return [x, y]; + } + } + // horizontally/vertically + else { + if (dx !== 0) { + if ((grid.isWalkableAt(x, y - 1) && !grid.isWalkableAt(x - dx, y - 1)) || + (grid.isWalkableAt(x, y + 1) && !grid.isWalkableAt(x - dx, y + 1))) { + return [x, y]; + } + } + else if (dy !== 0) { + if ((grid.isWalkableAt(x - 1, y) && !grid.isWalkableAt(x - 1, y - dy)) || + (grid.isWalkableAt(x + 1, y) && !grid.isWalkableAt(x + 1, y - dy))) { + return [x, y]; + } + // When moving vertically, must check for horizontal jump points + // if (this._jump(x + 1, y, x, y) || this._jump(x - 1, y, x, y)) { + // return [x, y]; + // } + } + } + + // moving diagonally, must make sure one of the vertical/horizontal + // neighbors is open to allow the path + if (grid.isWalkableAt(x + dx, y) && grid.isWalkableAt(x, y + dy)) { + return this._jump(x + dx, y + dy, x, y); + } else { + return null; + } +}; + +/** + * Find the neighbors for the given node. If the node has a parent, + * prune the neighbors based on the jump point search algorithm, otherwise + * return all available neighbors. + * @return {Array>} The neighbors found. + */ +JPFMoveDiagonallyIfNoObstacles.prototype._findNeighbors = function(node) { + var parent = node.parent, + x = node.x, y = node.y, + grid = this.grid, + px, py, nx, ny, dx, dy, + neighbors = [], neighborNodes, neighborNode, i, l; + + // directed pruning: can ignore most neighbors, unless forced. + if (parent) { + px = parent.x; + py = parent.y; + // get the normalized direction of travel + dx = (x - px) / Math.max(Math.abs(x - px), 1); + dy = (y - py) / Math.max(Math.abs(y - py), 1); + + // search diagonally + if (dx !== 0 && dy !== 0) { + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + } + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + } + if (grid.isWalkableAt(x, y + dy) && grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y + dy]); + } + } + // search horizontally/vertically + else { + var isNextWalkable; + if (dx !== 0) { + isNextWalkable = grid.isWalkableAt(x + dx, y); + var isTopWalkable = grid.isWalkableAt(x, y + 1); + var isBottomWalkable = grid.isWalkableAt(x, y - 1); + + if (isNextWalkable) { + neighbors.push([x + dx, y]); + if (isTopWalkable) { + neighbors.push([x + dx, y + 1]); + } + if (isBottomWalkable) { + neighbors.push([x + dx, y - 1]); + } + } + if (isTopWalkable) { + neighbors.push([x, y + 1]); + } + if (isBottomWalkable) { + neighbors.push([x, y - 1]); + } + } + else if (dy !== 0) { + isNextWalkable = grid.isWalkableAt(x, y + dy); + var isRightWalkable = grid.isWalkableAt(x + 1, y); + var isLeftWalkable = grid.isWalkableAt(x - 1, y); + + if (isNextWalkable) { + neighbors.push([x, y + dy]); + if (isRightWalkable) { + neighbors.push([x + 1, y + dy]); + } + if (isLeftWalkable) { + neighbors.push([x - 1, y + dy]); + } + } + if (isRightWalkable) { + neighbors.push([x + 1, y]); + } + if (isLeftWalkable) { + neighbors.push([x - 1, y]); + } + } + } + } + // return all neighbors + else { + neighborNodes = grid.getNeighbors(node, DiagonalMovement.OnlyWhenNoObstacles); + for (i = 0, l = neighborNodes.length; i < l; ++i) { + neighborNode = neighborNodes[i]; + neighbors.push([neighborNode.x, neighborNode.y]); + } + } + + return neighbors; +}; + +module.exports = JPFMoveDiagonallyIfNoObstacles; diff --git a/node_modules/pathfinding/src/finders/JPFNeverMoveDiagonally.js b/node_modules/pathfinding/src/finders/JPFNeverMoveDiagonally.js new file mode 100644 index 0000000..2f426b2 --- /dev/null +++ b/node_modules/pathfinding/src/finders/JPFNeverMoveDiagonally.js @@ -0,0 +1,120 @@ +/** + * @author imor / https://github.com/imor + */ +var JumpPointFinderBase = require('./JumpPointFinderBase'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Path finder using the Jump Point Search algorithm allowing only horizontal + * or vertical movements. + */ +function JPFNeverMoveDiagonally(opt) { + JumpPointFinderBase.call(this, opt); +} + +JPFNeverMoveDiagonally.prototype = new JumpPointFinderBase(); +JPFNeverMoveDiagonally.prototype.constructor = JPFNeverMoveDiagonally; + +/** + * Search recursively in the direction (parent -> child), stopping only when a + * jump point is found. + * @protected + * @return {Array>} The x, y coordinate of the jump point + * found, or null if not found + */ +JPFNeverMoveDiagonally.prototype._jump = function(x, y, px, py) { + var grid = this.grid, + dx = x - px, dy = y - py; + + if (!grid.isWalkableAt(x, y)) { + return null; + } + + if(this.trackJumpRecursion === true) { + grid.getNodeAt(x, y).tested = true; + } + + if (grid.getNodeAt(x, y) === this.endNode) { + return [x, y]; + } + + if (dx !== 0) { + if ((grid.isWalkableAt(x, y - 1) && !grid.isWalkableAt(x - dx, y - 1)) || + (grid.isWalkableAt(x, y + 1) && !grid.isWalkableAt(x - dx, y + 1))) { + return [x, y]; + } + } + else if (dy !== 0) { + if ((grid.isWalkableAt(x - 1, y) && !grid.isWalkableAt(x - 1, y - dy)) || + (grid.isWalkableAt(x + 1, y) && !grid.isWalkableAt(x + 1, y - dy))) { + return [x, y]; + } + //When moving vertically, must check for horizontal jump points + if (this._jump(x + 1, y, x, y) || this._jump(x - 1, y, x, y)) { + return [x, y]; + } + } + else { + throw new Error("Only horizontal and vertical movements are allowed"); + } + + return this._jump(x + dx, y + dy, x, y); +}; + +/** + * Find the neighbors for the given node. If the node has a parent, + * prune the neighbors based on the jump point search algorithm, otherwise + * return all available neighbors. + * @return {Array>} The neighbors found. + */ +JPFNeverMoveDiagonally.prototype._findNeighbors = function(node) { + var parent = node.parent, + x = node.x, y = node.y, + grid = this.grid, + px, py, nx, ny, dx, dy, + neighbors = [], neighborNodes, neighborNode, i, l; + + // directed pruning: can ignore most neighbors, unless forced. + if (parent) { + px = parent.x; + py = parent.y; + // get the normalized direction of travel + dx = (x - px) / Math.max(Math.abs(x - px), 1); + dy = (y - py) / Math.max(Math.abs(y - py), 1); + + if (dx !== 0) { + if (grid.isWalkableAt(x, y - 1)) { + neighbors.push([x, y - 1]); + } + if (grid.isWalkableAt(x, y + 1)) { + neighbors.push([x, y + 1]); + } + if (grid.isWalkableAt(x + dx, y)) { + neighbors.push([x + dx, y]); + } + } + else if (dy !== 0) { + if (grid.isWalkableAt(x - 1, y)) { + neighbors.push([x - 1, y]); + } + if (grid.isWalkableAt(x + 1, y)) { + neighbors.push([x + 1, y]); + } + if (grid.isWalkableAt(x, y + dy)) { + neighbors.push([x, y + dy]); + } + } + } + // return all neighbors + else { + neighborNodes = grid.getNeighbors(node, DiagonalMovement.Never); + for (i = 0, l = neighborNodes.length; i < l; ++i) { + neighborNode = neighborNodes[i]; + neighbors.push([neighborNode.x, neighborNode.y]); + } + } + + return neighbors; +}; + +module.exports = JPFNeverMoveDiagonally; diff --git a/node_modules/pathfinding/src/finders/JumpPointFinder.js b/node_modules/pathfinding/src/finders/JumpPointFinder.js new file mode 100644 index 0000000..d1a7c9e --- /dev/null +++ b/node_modules/pathfinding/src/finders/JumpPointFinder.js @@ -0,0 +1,31 @@ +/** + * @author aniero / https://github.com/aniero + */ +var DiagonalMovement = require('../core/DiagonalMovement'); +var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); +var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); +var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); +var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); + +/** + * Path finder using the Jump Point Search algorithm + * @param {Object} opt + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal + * movement will be allowed. + */ +function JumpPointFinder(opt) { + opt = opt || {}; + if (opt.diagonalMovement === DiagonalMovement.Never) { + return new JPFNeverMoveDiagonally(opt); + } else if (opt.diagonalMovement === DiagonalMovement.Always) { + return new JPFAlwaysMoveDiagonally(opt); + } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { + return new JPFMoveDiagonallyIfNoObstacles(opt); + } else { + return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); + } +} + +module.exports = JumpPointFinder; diff --git a/node_modules/pathfinding/src/finders/JumpPointFinderBase.js b/node_modules/pathfinding/src/finders/JumpPointFinderBase.js new file mode 100644 index 0000000..81a9042 --- /dev/null +++ b/node_modules/pathfinding/src/finders/JumpPointFinderBase.js @@ -0,0 +1,114 @@ +/** + * @author imor / https://github.com/imor + */ +var Heap = require('heap'); +var Util = require('../core/Util'); +var Heuristic = require('../core/Heuristic'); +var DiagonalMovement = require('../core/DiagonalMovement'); + +/** + * Base class for the Jump Point Search algorithm + * @param {object} opt + * @param {function} opt.heuristic Heuristic function to estimate the distance + * (defaults to manhattan). + */ +function JumpPointFinderBase(opt) { + opt = opt || {}; + this.heuristic = opt.heuristic || Heuristic.manhattan; + this.trackJumpRecursion = opt.trackJumpRecursion || false; +} + +/** + * Find and return the path. + * @return {Array>} The path, including both start and + * end positions. + */ +JumpPointFinderBase.prototype.findPath = function(startX, startY, endX, endY, grid) { + var openList = this.openList = new Heap(function(nodeA, nodeB) { + return nodeA.f - nodeB.f; + }), + startNode = this.startNode = grid.getNodeAt(startX, startY), + endNode = this.endNode = grid.getNodeAt(endX, endY), node; + + this.grid = grid; + + + // set the `g` and `f` value of the start node to be 0 + startNode.g = 0; + startNode.f = 0; + + // push the start node into the open list + openList.push(startNode); + startNode.opened = true; + + // while the open list is not empty + while (!openList.empty()) { + // pop the position of node which has the minimum `f` value. + node = openList.pop(); + node.closed = true; + + if (node === endNode) { + return Util.expandPath(Util.backtrace(endNode)); + } + + this._identifySuccessors(node); + } + + // fail to find the path + return []; +}; + +/** + * Identify successors for the given node. Runs a jump point search in the + * direction of each available neighbor, adding any points found to the open + * list. + * @protected + */ +JumpPointFinderBase.prototype._identifySuccessors = function(node) { + var grid = this.grid, + heuristic = this.heuristic, + openList = this.openList, + endX = this.endNode.x, + endY = this.endNode.y, + neighbors, neighbor, + jumpPoint, i, l, + x = node.x, y = node.y, + jx, jy, dx, dy, d, ng, jumpNode, + abs = Math.abs, max = Math.max; + + neighbors = this._findNeighbors(node); + for(i = 0, l = neighbors.length; i < l; ++i) { + neighbor = neighbors[i]; + jumpPoint = this._jump(neighbor[0], neighbor[1], x, y); + if (jumpPoint) { + + jx = jumpPoint[0]; + jy = jumpPoint[1]; + jumpNode = grid.getNodeAt(jx, jy); + + if (jumpNode.closed) { + continue; + } + + // include distance, as parent may not be immediately adjacent: + d = Heuristic.octile(abs(jx - x), abs(jy - y)); + ng = node.g + d; // next `g` value + + if (!jumpNode.opened || ng < jumpNode.g) { + jumpNode.g = ng; + jumpNode.h = jumpNode.h || heuristic(abs(jx - endX), abs(jy - endY)); + jumpNode.f = jumpNode.g + jumpNode.h; + jumpNode.parent = node; + + if (!jumpNode.opened) { + openList.push(jumpNode); + jumpNode.opened = true; + } else { + openList.updateItem(jumpNode); + } + } + } + } +}; + +module.exports = JumpPointFinderBase; diff --git a/node_modules/pathfinding/test/Grid.js b/node_modules/pathfinding/test/Grid.js new file mode 100644 index 0000000..123ccfa --- /dev/null +++ b/node_modules/pathfinding/test/Grid.js @@ -0,0 +1,155 @@ +var PF = require('..'); +var Grid = PF.Grid; +var DiagonalMovement = PF.DiagonalMovement; + +describe('Grid', function() { + describe('generate without matrix', function() { + var width, height, grid; + + beforeEach(function() { + width = 10; + height = 20; + grid = new Grid(width, height); + }); + + it('should have correct size', function() { + grid.width.should.equal(width); + grid.height.should.equal(height); + + grid.nodes.length.should.equal(height); + for (var i = 0; i < height; ++i) { + grid.nodes[i].length.should.equal(width); + } + }); + + it('should set all nodes\' walkable attribute', function() { + for (var i = 0; i < height; ++i) { + for (var j = 0; j < width; ++j) { + grid.isWalkableAt(j, i).should.be.true; + } + } + }); + }); + + describe('generate with matrix', function() { + var matrix, grid, width, height; + + var enumPos = function(f, o) { + for (var y = 0; y < height; ++y) { + for (var x = 0; x < width; ++x) { + if (o) { + f.call(o, x, y, grid); + } else { + f(x, y, grid); + } + } + } + }; + + beforeEach(function() { + matrix = [ + [1, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 1], + ]; + height = matrix.length; + width = matrix[0].length; + grid = new Grid(width, height, matrix); + }); + + it('should have correct size', function() { + grid.width.should.equal(width); + grid.height.should.equal(height); + + grid.nodes.length.should.equal(height); + for (var i = 0; i < height; ++i) { + grid.nodes[i].length.should.equal(width); + } + }); + + it('should initiate all nodes\' walkable attribute', function() { + enumPos(function(x, y, g) { + if (matrix[y][x]) { + g.isWalkableAt(x, y).should.be.false; + } else { + g.isWalkableAt(x, y).should.be.true; + } + }); + }); + + it('should be able to set nodes\' walkable attribute', function() { + enumPos(function(x, y) { + grid.setWalkableAt(x, y, false); + }); + enumPos(function(x, y) { + grid.isWalkableAt(x, y).should.be.false; + }) + enumPos(function(x, y) { + grid.setWalkableAt(x, y, true); + }); + enumPos(function(x, y) { + grid.isWalkableAt(x, y).should.be.true; + }) + }); + + it('should return correct answer for position validity query', function() { + var asserts = [ + [0, 0, true], + [0, height - 1, true], + [width - 1, 0, true], + [width - 1, height - 1, true], + [-1, -1, false], + [0, -1, false], + [-1, 0, false], + [0, height, false], + [width, 0, false], + [width, height, false], + ]; + + asserts.forEach(function(v, i, a) { + grid.isInside(v[0], v[1]).should.equal(v[2]); + }); + }); + + it('should return correct neighbors', function() { + grid.getNeighbors(grid.nodes[1][0], DiagonalMovement.Never).should.eql([ grid.nodes[2][0] ]); + var cmp = function(a, b) { + return a.x * 100 + a.y - b.x * 100 - b.y; + }; + grid.getNeighbors(grid.nodes[0][2], DiagonalMovement.IfAtMostOneObstacle).sort(cmp).should.eql([ + grid.nodes[0][1], grid.nodes[1][2], grid.nodes[1][3] + ].sort(cmp)) + }); + }); + + describe('generate with matrix and no width or height', function() { + var matrix, grid; + + beforeEach(function() { + matrix = [ + [1, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 1], + ]; + + grid = new Grid(matrix); + }); + + it('should have correct size', function() { + var height = matrix.length; + var width = matrix[0].length; + + grid.width.should.equal(width); + grid.height.should.equal(height); + + grid.nodes.length.should.equal(height); + for (var i = 0; i < height; ++i) { + grid.nodes[i].length.should.equal(width); + } + }); + }); +}); diff --git a/node_modules/pathfinding/test/PathTest.js b/node_modules/pathfinding/test/PathTest.js new file mode 100644 index 0000000..ce2ed05 --- /dev/null +++ b/node_modules/pathfinding/test/PathTest.js @@ -0,0 +1,112 @@ +var PF = require('..') +var scenarios = require('./PathTestScenarios'); + +/** + * Path-finding tests for the path-finders. + * @param {boolean} opt.optimal - Whether the finder is guaranteed to find the shortest path + */ +function pathTest(opt) { + var name = opt.name, + finder = opt.finder, + optimal = opt.optimal; + + describe(name, function() { + var startX, startY, endX, endY, grid, expectedLength, + width, height, matrix, path, i, scen; + + var test = (function() { + var testId = 0; + + return function(startX, startY, endX, endY, grid, expectedLength) { + it('should solve maze '+ ++testId, function() { + path = finder.findPath(startX, startY, endX, endY, grid); + if (optimal) { + path.length.should.equal(expectedLength); + } else { + path[0].should.eql([startX, startY]); + path[path.length - 1].should.eql([endX, endY]); + } + }); + }; + })(); + + // Load all the scenarios and test against the finder. + for (i = 0; i < scenarios.length; ++i) { + scen = scenarios[i]; + + matrix = scen.matrix; + height = matrix.length; + width = matrix[0].length; + + grid = new PF.Grid(width, height, matrix); + + test( + scen.startX, scen.startY, + scen.endX, scen.endY, + grid, + scen.expectedLength + ); + } + }); +} + +function pathTests(tests) { + for (i = 0; i < arguments.length; ++i) { + pathTest(arguments[i]); + } +} + + +// finders guaranteed to find the shortest path +pathTests({ + name: 'AStar', + finder: new PF.AStarFinder(), + optimal: true +}, { + name: 'BreadthFirst', + finder: new PF.BreadthFirstFinder(), + optimal: true +}, { + name: 'Dijkstra', + finder: new PF.DijkstraFinder(), + optimal: true +}, { + name: 'BiBreadthFirst', + finder: new PF.BiBreadthFirstFinder(), + optimal: true +}, { + name: 'BiDijkstra', + finder: new PF.BiDijkstraFinder(), + optimal: true +}); + +// finders NOT guaranteed to find the shortest path +pathTests({ + name: 'BiAStar', + finder: new PF.BiAStarFinder(), + optimal: false +}, { + name: 'BestFirst', + finder: new PF.BestFirstFinder(), + optimal: false +}, { + name: 'BiBestFirst', + finder: new PF.BiBestFirstFinder(), + optimal: false +}, { + name: 'IDAStar', + finder: new PF.IDAStarFinder(), + optimal: false +}, { + name: 'JPFMoveDiagonallyIfAtMostOneObstacle', + finder: new PF.JumpPointFinder({ + diagonalMovement: PF.DiagonalMovement.IfAtMostOneObstacle + }), + optimal: false +}, { + name: 'JPFNeverMoveDiagonally', + finder: new PF.JumpPointFinder({ + diagonalMovement: PF.DiagonalMovement.Never + }), + optimal: false +}); diff --git a/node_modules/pathfinding/test/PathTestScenarios.js b/node_modules/pathfinding/test/PathTestScenarios.js new file mode 100644 index 0000000..c70aa5b --- /dev/null +++ b/node_modules/pathfinding/test/PathTestScenarios.js @@ -0,0 +1,64 @@ +module.exports = [ + { + startX: 0, + startY: 0, + endX: 1, + endY: 1, + matrix: [[0, 0], + [1, 0]], + expectedLength: 3, + }, + { + startX: 1, + startY: 1, + endX: 4, + endY: 4, + matrix: [[0, 0, 0, 0, 0], + [1, 0, 1, 1, 0], + [1, 0, 1, 0, 0], + [0, 1, 0, 0, 0], + [1, 0, 1, 1, 0], + [0, 0, 1, 0, 0]], + expectedLength: 9, + }, + { + startX: 0, + startY: 3, + endX: 3, + endY: 3, + matrix: [[0, 0, 0, 0, 0], + [0, 0, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [1, 0, 1, 1, 0], + [0, 0, 0, 0, 0]], + expectedLength: 10, + }, + { + startX: 4,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + expectedLength: 31, + }, +]; diff --git a/node_modules/pathfinding/test/Util.js b/node_modules/pathfinding/test/Util.js new file mode 100644 index 0000000..eb2f57c --- /dev/null +++ b/node_modules/pathfinding/test/Util.js @@ -0,0 +1,52 @@ +var PF = require('..'); + +describe('Utility functions', function () { + describe('interpolate', function () { + it('should return the interpolated path', function () { + PF.Util.interpolate(0, 1, 0, 4).should.eql([ + [0, 1], [0, 2], [0, 3], [0, 4] + ]); + }); + }); + + describe('expandPath', function () { + it('should return an empty array given an empty array', function () { + PF.Util.expandPath([]).should.eql([]); + }); + + it('should return the expanded path', function () { + PF.Util.expandPath([ + [0, 1], [0, 4] + ]).should.eql([ + [0, 1], [0, 2], [0, 3], [0, 4] + ]); + + PF.Util.expandPath([ + [0, 1], [0, 4], [2, 6] + ]).should.eql([ + [0, 1], [0, 2], [0, 3], [0, 4], [1, 5], [2, 6] + ]); + }); + }); + + describe('compressPath', function () { + it('should return the original path if it is too short to compress', function () { + PF.Util.compressPath([]).should.eql([]); + }); + + it('should return a compressed path', function () { + PF.Util.compressPath([ + [0, 1], [0, 2], [0, 3], [0, 4] + ]).should.eql([ + [0, 1], [0, 4] + ]); + + PF.Util.compressPath([ + [0, 1], [0, 2], [0, 3], [0, 4], [1, 5], [2, 6] + ]).should.eql([ + [0, 1], [0, 4], [2, 6] + ]); + }); + }); + +}); diff --git a/node_modules/pathfinding/visual/Makefile b/node_modules/pathfinding/visual/Makefile new file mode 100644 index 0000000..28570d8 --- /dev/null +++ b/node_modules/pathfinding/visual/Makefile @@ -0,0 +1,5 @@ + +doc: doc/state-diagram.gv + dot -Tpng -odoc/state-diagram.png doc/state-diagram.gv + +.PHONY: doc diff --git a/node_modules/pathfinding/visual/css/style.css b/node_modules/pathfinding/visual/css/style.css new file mode 100644 index 0000000..3ec1f36 --- /dev/null +++ b/node_modules/pathfinding/visual/css/style.css @@ -0,0 +1,143 @@ +body { + padding: 0px; + margin: 0px; + overflow: hidden; +} + +input { + cursor: pointer; +} + +h1, h2, h3, h4, h5, h6 { + margin: 0px; + padding: 0px; + font-weight: normal; +} + +.header_title { + font-size: 120%; + font-weight: bold; + padding-bottom: 5px; + margin-top: -10px; +} + + +.panel { + position: fixed; + padding: 20px; + background-color: rgba(0, 0, 0, 0.6); + color: #fff; + border-radius: 8px; + box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5); + cursor: default; +} + +.right_panel { + width: 250px; + right: 20px; +} + +#algorithm_panel { + right: 20px; + top: 20px; +} + +#instructions_panel { + top: 20px; + left: 20px; + width: 550px; +} + +#hide_instructions { + position: absolute; + right: 25px; + top: 10px; + font-size: 90%; + cursor: pointer; +} + +#hide_instruction:hover { + color: #fff; + text-decoration: underline; +} + +.option_header { + font-size: 80%; + margin-left: 20px; +} + +.option_label { + cursor: pointer; +} + +button { + border: none; + background: rgba(255, 255, 255, 0.7); + border-radius: 5px; + font-size: 90%; + cursor: pointer; + padding: 2px 8px; + margin: 0 2%; + width: 28%; +} + +button:hover { + background: rgba(255, 255, 255, 0.9); +} + +.finder_section { + border: solid 1px #ddd; + border-radius: 5px; + margin: 5px; +} + +.sub_options { + padding: 2px; + font-size: 14px; + margin: 2px 30px 0; +} + +#stats { + position: fixed; + bottom: 40px; + left: 35px; + color: #0a0; + font-size: 85%; + padding: 5px; + background: rgba(255, 255, 255, 0.5); + border-radius: 5px; +} + +a { + color: #33f; +} + +footer { + color: #333; + font-size: 70%; + text-align: center; + position: fixed; + width: 200px; + bottom: 10px; + left: 50%; + margin-left: -100px; + background: rgba(255, 255, 255, 0.5); + padding: 5px; + border-radius: 5px; +} + +.white { + color: #fff; +} + +.green { + color: #0d0; +} + +.red { + color: #ff9166; +} + +.spinner { + width: 2em; +} diff --git a/node_modules/pathfinding/visual/doc/state-description.md b/node_modules/pathfinding/visual/doc/state-description.md new file mode 100644 index 0000000..08095aa --- /dev/null +++ b/node_modules/pathfinding/visual/doc/state-description.md @@ -0,0 +1,30 @@ +From [issue 6](https://github.com/qiao/PathFinding.js/issues/6) + +#### states and button labels/actions + +##### before searching; no colored squares - state B +- **Start Search** - to N +- **Pause Search** - button disabled (grayed out) + +##### starting a new search - state N +This state clears any existing search progress and then immediately goes to state S. + +##### during searching - state S +- **Restart Search** - to N +- **Pause Search** - to P + +when search has finished - to F + +##### search is paused - state P +- **Resume Search** - to S +- **Cancel Search** - to B + +##### search has finished - state F +- **Restart Search** - to N +- **Clear Path** - to B + +selecting a different algorithm or adding or deleting walls - to M + +##### after search has finished and user has changed settings - state M +- **Start Search** - to N +- **Clear Path** - to B diff --git a/node_modules/pathfinding/visual/doc/state-diagram.gv b/node_modules/pathfinding/visual/doc/state-diagram.gv new file mode 100644 index 0000000..aa4e94f --- /dev/null +++ b/node_modules/pathfinding/visual/doc/state-diagram.gv @@ -0,0 +1,19 @@ +digraph controller_states { + rankdir=LR; + size="10,8" + node [shape = circle]; + none -> before [ label = "init" ]; + before -> starting [ label = "start" ]; + starting -> searching [ label = "search" ]; + searching -> starting [ label = "restart" ]; + searching -> paused [ label = "pause" ]; + searching -> finished [ label = "finish" ]; + paused -> searching [ label = "resume" ]; + paused -> before [ label = "cancel" ]; + finished -> starting [ label = "restart" ]; + finished -> before [ label = "clear" ]; + finished -> modified [ label = "modify" ]; + modified -> starting [ label = "start" ]; + modified -> before [ label = "clear" ]; +} + diff --git a/node_modules/pathfinding/visual/doc/state-diagram.png b/node_modules/pathfinding/visual/doc/state-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..af6c63df12e64ca642985cb0571ce8cd7b707007 GIT binary patch literal 49802 zcmZsD2RxO181|uz5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j-3MR=#Rm!9Y-QOWqk z5S0fop&<2#_wBp;VI4>>xz06|+>_PIKdigPF2cz424c7&Bh2H{;8HM`tb?jY7#x&4 zP>8uLgY@--zCRuV07j!S5j@{QQPiz_q-Dp=5sxKgTMlnjdK=NP{@bWoJ|Zb53l~3l zAc({GtqA+bg2>qUkSCCBXF0bOv)f#(JN*z{Q0fTmQ0>iJ4rYFSl7oZ6ph2vd+%{j~ z;teWRwIaX?`Sqb6oM>sOs}QmJh=u8PH$J%iaKajUhk2KH$YC`;=HSl66FwAj=9m@I()%AO$jV-4fCpC4@PpRxT{)T6CSYndYE%pV z2O$@{Kjg*kAThQ1YtQ6H1~!M8S-cxHTfu0M=k1#Bzff;_FUL=G=kDEevpmE9$FXr1 z)ZK8cSL)mM5{<;&?YZ6U43;li@1D~O4IB-4B*?rvXMJVsW^dsauBXy8_o=eMrDJeP z(6@qK)=m)V4fdW90p;dj!^Fo|go)MX_YGS0OdT&3 zg1i&OG9}{AkR^jXLyXYOFj-ygI+6#FcSt8qRn^hMW_k!Fi@-j^jA~z3VE8)OnVN>tPzRuo6q;l6GyaFxJgvD$=N>Er}vJQlNXw6L}d<*nqb7rURCRd`@uhFaDd-xRhuC%?a{hQf4*^Awu(& zyI#lyMsf=9@lcqh@+OTs&EI#akGicn$($p946&ad<2+ie)@1$;S#&kwq z3z3V)4s693!a)T3_qNI8bL|Q$^$ zjXVE5t>HEEqPC%K=yaW>XN)2%y4F5e&_Jo1jC*bwgY2mer6bAwf z!7pq!2v5nmxnYL*c89~vWw9A87O)39TbWRsg(>icJ4Sb{Nm~a(&!K=K0jR>Dr!+It z9`$rLSxSIeQht?S##A)_z6G&?*v6rVtyxc56T_1px&^eK@wG)N%-oVME + + + + PathFinding.js + + + + + + + + + + + + + + + + + + + + + + + + + +

+ +
+
+

Instructions

+ hide +
+ Click within the white grid and drag your mouse to draw obstacles.
+ Drag the green node to set the start position.
+ Drag the red node to set the end position.
+ Choose an algorithm from the right-hand panel.
+ Click Start Search in the lower-right corner to start the animation. +
+ +
+

Select Algorithm

+ +
+

A*

+
+
+

Heuristic

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

Options

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

IDA*

+
+
+

Heuristic

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

Options

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

Breadth-First-Search

+
+
+

Options

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

Best-First-Search

+
+
+

Heuristic

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

Options

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

Dijkstra

+
+
+

Options

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

Jump Point Search

+
+
+

Heuristic

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

Options

+
+
+ +
+
+
+ +

Orthogonal Jump Point Search

+
+
+

Heuristic

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

Options

+
+
+ +
+
+
+ +
+
+ +
+ + + +
+ +
+ +
+ Project Hosted on Github +
+ + + diff --git a/node_modules/pathfinding/visual/js/controller.js b/node_modules/pathfinding/visual/js/controller.js new file mode 100644 index 0000000..a4623b3 --- /dev/null +++ b/node_modules/pathfinding/visual/js/controller.js @@ -0,0 +1,507 @@ +/** + * The visualization controller will works as a state machine. + * See files under the `doc` folder for transition descriptions. + * See https://github.com/jakesgordon/javascript-state-machine + * for the document of the StateMachine module. + */ +var Controller = StateMachine.create({ + initial: 'none', + events: [ + { + name: 'init', + from: 'none', + to: 'ready' + }, + { + name: 'search', + from: 'starting', + to: 'searching' + }, + { + name: 'pause', + from: 'searching', + to: 'paused' + }, + { + name: 'finish', + from: 'searching', + to: 'finished' + }, + { + name: 'resume', + from: 'paused', + to: 'searching' + }, + { + name: 'cancel', + from: 'paused', + to: 'ready' + }, + { + name: 'modify', + from: 'finished', + to: 'modified' + }, + { + name: 'reset', + from: '*', + to: 'ready' + }, + { + name: 'clear', + from: ['finished', 'modified'], + to: 'ready' + }, + { + name: 'start', + from: ['ready', 'modified', 'restarting'], + to: 'starting' + }, + { + name: 'restart', + from: ['searching', 'finished'], + to: 'restarting' + }, + { + name: 'dragStart', + from: ['ready', 'finished'], + to: 'draggingStart' + }, + { + name: 'dragEnd', + from: ['ready', 'finished'], + to: 'draggingEnd' + }, + { + name: 'drawWall', + from: ['ready', 'finished'], + to: 'drawingWall' + }, + { + name: 'eraseWall', + from: ['ready', 'finished'], + to: 'erasingWall' + }, + { + name: 'rest', + from: ['draggingStart', 'draggingEnd', 'drawingWall', 'erasingWall'], + to : 'ready' + }, + ], +}); + +$.extend(Controller, { + gridSize: [64, 36], // number of nodes horizontally and vertically + operationsPerSecond: 300, + + /** + * Asynchronous transition from `none` state to `ready` state. + */ + onleavenone: function() { + var numCols = this.gridSize[0], + numRows = this.gridSize[1]; + + this.grid = new PF.Grid(numCols, numRows); + + View.init({ + numCols: numCols, + numRows: numRows + }); + View.generateGrid(function() { + Controller.setDefaultStartEndPos(); + Controller.bindEvents(); + Controller.transition(); // transit to the next state (ready) + }); + + this.$buttons = $('.control_button'); + + this.hookPathFinding(); + + return StateMachine.ASYNC; + // => ready + }, + ondrawWall: function(event, from, to, gridX, gridY) { + this.setWalkableAt(gridX, gridY, false); + // => drawingWall + }, + oneraseWall: function(event, from, to, gridX, gridY) { + this.setWalkableAt(gridX, gridY, true); + // => erasingWall + }, + onsearch: function(event, from, to) { + var grid, + timeStart, timeEnd, + finder = Panel.getFinder(); + + timeStart = window.performance ? performance.now() : Date.now(); + grid = this.grid.clone(); + this.path = finder.findPath( + this.startX, this.startY, this.endX, this.endY, grid + ); + this.operationCount = this.operations.length; + timeEnd = window.performance ? performance.now() : Date.now(); + this.timeSpent = (timeEnd - timeStart).toFixed(4); + + this.loop(); + // => searching + }, + onrestart: function() { + // When clearing the colorized nodes, there may be + // nodes still animating, which is an asynchronous procedure. + // Therefore, we have to defer the `abort` routine to make sure + // that all the animations are done by the time we clear the colors. + // The same reason applies for the `onreset` event handler. + setTimeout(function() { + Controller.clearOperations(); + Controller.clearFootprints(); + Controller.start(); + }, View.nodeColorizeEffect.duration * 1.2); + // => restarting + }, + onpause: function(event, from, to) { + // => paused + }, + onresume: function(event, from, to) { + this.loop(); + // => searching + }, + oncancel: function(event, from, to) { + this.clearOperations(); + this.clearFootprints(); + // => ready + }, + onfinish: function(event, from, to) { + View.showStats({ + pathLength: PF.Util.pathLength(this.path), + timeSpent: this.timeSpent, + operationCount: this.operationCount, + }); + View.drawPath(this.path); + // => finished + }, + onclear: function(event, from, to) { + this.clearOperations(); + this.clearFootprints(); + // => ready + }, + onmodify: function(event, from, to) { + // => modified + }, + onreset: function(event, from, to) { + setTimeout(function() { + Controller.clearOperations(); + Controller.clearAll(); + Controller.buildNewGrid(); + }, View.nodeColorizeEffect.duration * 1.2); + // => ready + }, + + /** + * The following functions are called on entering states. + */ + + onready: function() { + console.log('=> ready'); + this.setButtonStates({ + id: 1, + text: 'Start Search', + enabled: true, + callback: $.proxy(this.start, this), + }, { + id: 2, + text: 'Pause Search', + enabled: false, + }, { + id: 3, + text: 'Clear Walls', + enabled: true, + callback: $.proxy(this.reset, this), + }); + // => [starting, draggingStart, draggingEnd, drawingStart, drawingEnd] + }, + onstarting: function(event, from, to) { + console.log('=> starting'); + // Clears any existing search progress + this.clearFootprints(); + this.setButtonStates({ + id: 2, + enabled: true, + }); + this.search(); + // => searching + }, + onsearching: function() { + console.log('=> searching'); + this.setButtonStates({ + id: 1, + text: 'Restart Search', + enabled: true, + callback: $.proxy(this.restart, this), + }, { + id: 2, + text: 'Pause Search', + enabled: true, + callback: $.proxy(this.pause, this), + }); + // => [paused, finished] + }, + onpaused: function() { + console.log('=> paused'); + this.setButtonStates({ + id: 1, + text: 'Resume Search', + enabled: true, + callback: $.proxy(this.resume, this), + }, { + id: 2, + text: 'Cancel Search', + enabled: true, + callback: $.proxy(this.cancel, this), + }); + // => [searching, ready] + }, + onfinished: function() { + console.log('=> finished'); + this.setButtonStates({ + id: 1, + text: 'Restart Search', + enabled: true, + callback: $.proxy(this.restart, this), + }, { + id: 2, + text: 'Clear Path', + enabled: true, + callback: $.proxy(this.clear, this), + }); + }, + onmodified: function() { + console.log('=> modified'); + this.setButtonStates({ + id: 1, + text: 'Start Search', + enabled: true, + callback: $.proxy(this.start, this), + }, { + id: 2, + text: 'Clear Path', + enabled: true, + callback: $.proxy(this.clear, this), + }); + }, + + /** + * Define setters and getters of PF.Node, then we can get the operations + * of the pathfinding. + */ + hookPathFinding: function() { + + PF.Node.prototype = { + get opened() { + return this._opened; + }, + set opened(v) { + this._opened = v; + Controller.operations.push({ + x: this.x, + y: this.y, + attr: 'opened', + value: v + }); + }, + get closed() { + return this._closed; + }, + set closed(v) { + this._closed = v; + Controller.operations.push({ + x: this.x, + y: this.y, + attr: 'closed', + value: v + }); + }, + get tested() { + return this._tested; + }, + set tested(v) { + this._tested = v; + Controller.operations.push({ + x: this.x, + y: this.y, + attr: 'tested', + value: v + }); + }, + }; + + this.operations = []; + }, + bindEvents: function() { + $('#draw_area').mousedown($.proxy(this.mousedown, this)); + $(window) + .mousemove($.proxy(this.mousemove, this)) + .mouseup($.proxy(this.mouseup, this)); + }, + loop: function() { + var interval = 1000 / this.operationsPerSecond; + (function loop() { + if (!Controller.is('searching')) { + return; + } + Controller.step(); + setTimeout(loop, interval); + })(); + }, + step: function() { + var operations = this.operations, + op, isSupported; + + do { + if (!operations.length) { + this.finish(); // transit to `finished` state + return; + } + op = operations.shift(); + isSupported = View.supportedOperations.indexOf(op.attr) !== -1; + } while (!isSupported); + + View.setAttributeAt(op.x, op.y, op.attr, op.value); + }, + clearOperations: function() { + this.operations = []; + }, + clearFootprints: function() { + View.clearFootprints(); + View.clearPath(); + }, + clearAll: function() { + this.clearFootprints(); + View.clearBlockedNodes(); + }, + buildNewGrid: function() { + this.grid = new PF.Grid(this.gridSize[0], this.gridSize[1]); + }, + mousedown: function (event) { + var coord = View.toGridCoordinate(event.pageX, event.pageY), + gridX = coord[0], + gridY = coord[1], + grid = this.grid; + + if (this.can('dragStart') && this.isStartPos(gridX, gridY)) { + this.dragStart(); + return; + } + if (this.can('dragEnd') && this.isEndPos(gridX, gridY)) { + this.dragEnd(); + return; + } + if (this.can('drawWall') && grid.isWalkableAt(gridX, gridY)) { + this.drawWall(gridX, gridY); + return; + } + if (this.can('eraseWall') && !grid.isWalkableAt(gridX, gridY)) { + this.eraseWall(gridX, gridY); + } + }, + mousemove: function(event) { + var coord = View.toGridCoordinate(event.pageX, event.pageY), + grid = this.grid, + gridX = coord[0], + gridY = coord[1]; + + if (this.isStartOrEndPos(gridX, gridY)) { + return; + } + + switch (this.current) { + case 'draggingStart': + if (grid.isWalkableAt(gridX, gridY)) { + this.setStartPos(gridX, gridY); + } + break; + case 'draggingEnd': + if (grid.isWalkableAt(gridX, gridY)) { + this.setEndPos(gridX, gridY); + } + break; + case 'drawingWall': + this.setWalkableAt(gridX, gridY, false); + break; + case 'erasingWall': + this.setWalkableAt(gridX, gridY, true); + break; + } + }, + mouseup: function(event) { + if (Controller.can('rest')) { + Controller.rest(); + } + }, + setButtonStates: function() { + $.each(arguments, function(i, opt) { + var $button = Controller.$buttons.eq(opt.id - 1); + if (opt.text) { + $button.text(opt.text); + } + if (opt.callback) { + $button + .unbind('click') + .click(opt.callback); + } + if (opt.enabled === undefined) { + return; + } else if (opt.enabled) { + $button.removeAttr('disabled'); + } else { + $button.attr({ disabled: 'disabled' }); + } + }); + }, + /** + * When initializing, this method will be called to set the positions + * of start node and end node. + * It will detect user's display size, and compute the best positions. + */ + setDefaultStartEndPos: function() { + var width, height, + marginRight, availWidth, + centerX, centerY, + endX, endY, + nodeSize = View.nodeSize; + + width = $(window).width(); + height = $(window).height(); + + marginRight = $('#algorithm_panel').width(); + availWidth = width - marginRight; + + centerX = Math.ceil(availWidth / 2 / nodeSize); + centerY = Math.floor(height / 2 / nodeSize); + + this.setStartPos(centerX - 5, centerY); + this.setEndPos(centerX + 5, centerY); + }, + setStartPos: function(gridX, gridY) { + this.startX = gridX; + this.startY = gridY; + View.setStartPos(gridX, gridY); + }, + setEndPos: function(gridX, gridY) { + this.endX = gridX; + this.endY = gridY; + View.setEndPos(gridX, gridY); + }, + setWalkableAt: function(gridX, gridY, walkable) { + this.grid.setWalkableAt(gridX, gridY, walkable); + View.setAttributeAt(gridX, gridY, 'walkable', walkable); + }, + isStartPos: function(gridX, gridY) { + return gridX === this.startX && gridY === this.startY; + }, + isEndPos: function(gridX, gridY) { + return gridX === this.endX && gridY === this.endY; + }, + isStartOrEndPos: function(gridX, gridY) { + return this.isStartPos(gridX, gridY) || this.isEndPos(gridX, gridY); + }, +}); diff --git a/node_modules/pathfinding/visual/js/main.js b/node_modules/pathfinding/visual/js/main.js new file mode 100644 index 0000000..274b7b3 --- /dev/null +++ b/node_modules/pathfinding/visual/js/main.js @@ -0,0 +1,14 @@ +$(document).ready(function() { + if (!Raphael.svg) { + window.location = './notsupported.html'; + } + + // suppress select events + $(window).bind('selectstart', function(event) { + event.preventDefault(); + }); + + // initialize visualization + Panel.init(); + Controller.init(); +}); diff --git a/node_modules/pathfinding/visual/js/panel.js b/node_modules/pathfinding/visual/js/panel.js new file mode 100644 index 0000000..d26e830 --- /dev/null +++ b/node_modules/pathfinding/visual/js/panel.js @@ -0,0 +1,184 @@ +/** + * The control panel. + */ +var Panel = { + init: function() { + var $algo = $('#algorithm_panel'); + + $('.panel').draggable(); + $('.accordion').accordion({ + collapsible: false, + }); + $('.option_label').click(function() { + $(this).prev().click(); + }); + $('#hide_instructions').click(function() { + $('#instructions_panel').slideUp(); + }); + $('#play_panel').css({ + top: $algo.offset().top + $algo.outerHeight() + 20 + }); + $('#button2').attr('disabled', 'disabled'); + }, + /** + * Get the user selected path-finder. + * TODO: clean up this messy code. + */ + getFinder: function() { + var finder, selected_header, heuristic, allowDiagonal, biDirectional, dontCrossCorners, weight, trackRecursion, timeLimit; + + selected_header = $( + '#algorithm_panel ' + + '.ui-accordion-header[aria-selected=true]' + ).attr('id'); + + switch (selected_header) { + + case 'astar_header': + allowDiagonal = typeof $('#astar_section ' + + '.allow_diagonal:checked').val() !== 'undefined'; + biDirectional = typeof $('#astar_section ' + + '.bi-directional:checked').val() !=='undefined'; + dontCrossCorners = typeof $('#astar_section ' + + '.dont_cross_corners:checked').val() !=='undefined'; + + /* parseInt returns NaN (which is falsy) if the string can't be parsed */ + weight = parseInt($('#astar_section .spinner').val()) || 1; + weight = weight >= 1 ? weight : 1; /* if negative or 0, use 1 */ + + heuristic = $('input[name=astar_heuristic]:checked').val(); + if (biDirectional) { + finder = new PF.BiAStarFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners, + heuristic: PF.Heuristic[heuristic], + weight: weight + }); + } else { + finder = new PF.AStarFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners, + heuristic: PF.Heuristic[heuristic], + weight: weight + }); + } + break; + + case 'breadthfirst_header': + allowDiagonal = typeof $('#breadthfirst_section ' + + '.allow_diagonal:checked').val() !== 'undefined'; + biDirectional = typeof $('#breadthfirst_section ' + + '.bi-directional:checked').val() !== 'undefined'; + dontCrossCorners = typeof $('#breadthfirst_section ' + + '.dont_cross_corners:checked').val() !=='undefined'; + if (biDirectional) { + finder = new PF.BiBreadthFirstFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners + }); + } else { + finder = new PF.BreadthFirstFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners + }); + } + break; + + case 'bestfirst_header': + allowDiagonal = typeof $('#bestfirst_section ' + + '.allow_diagonal:checked').val() !== 'undefined'; + biDirectional = typeof $('#bestfirst_section ' + + '.bi-directional:checked').val() !== 'undefined'; + dontCrossCorners = typeof $('#bestfirst_section ' + + '.dont_cross_corners:checked').val() !=='undefined'; + heuristic = $('input[name=bestfirst_heuristic]:checked').val(); + if (biDirectional) { + finder = new PF.BiBestFirstFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners, + heuristic: PF.Heuristic[heuristic] + }); + } else { + finder = new PF.BestFirstFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners, + heuristic: PF.Heuristic[heuristic] + }); + } + break; + + case 'dijkstra_header': + allowDiagonal = typeof $('#dijkstra_section ' + + '.allow_diagonal:checked').val() !== 'undefined'; + biDirectional = typeof $('#dijkstra_section ' + + '.bi-directional:checked').val() !=='undefined'; + dontCrossCorners = typeof $('#dijkstra_section ' + + '.dont_cross_corners:checked').val() !=='undefined'; + if (biDirectional) { + finder = new PF.BiDijkstraFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners + }); + } else { + finder = new PF.DijkstraFinder({ + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners + }); + } + break; + + case 'jump_point_header': + trackRecursion = typeof $('#jump_point_section ' + + '.track_recursion:checked').val() !== 'undefined'; + heuristic = $('input[name=jump_point_heuristic]:checked').val(); + + finder = new PF.JumpPointFinder({ + trackJumpRecursion: trackRecursion, + heuristic: PF.Heuristic[heuristic], + diagonalMovement: PF.DiagonalMovement.IfAtMostOneObstacle + }); + break; + case 'orth_jump_point_header': + trackRecursion = typeof $('#orth_jump_point_section ' + + '.track_recursion:checked').val() !== 'undefined'; + heuristic = $('input[name=orth_jump_point_heuristic]:checked').val(); + + finder = new PF.JumpPointFinder({ + trackJumpRecursion: trackRecursion, + heuristic: PF.Heuristic[heuristic], + diagonalMovement: PF.DiagonalMovement.Never + }); + break; + case 'ida_header': + allowDiagonal = typeof $('#ida_section ' + + '.allow_diagonal:checked').val() !== 'undefined'; + dontCrossCorners = typeof $('#ida_section ' + + '.dont_cross_corners:checked').val() !=='undefined'; + trackRecursion = typeof $('#ida_section ' + + '.track_recursion:checked').val() !== 'undefined'; + + heuristic = $('input[name=jump_point_heuristic]:checked').val(); + + weight = parseInt($('#ida_section input[name=astar_weight]').val()) || 1; + weight = weight >= 1 ? weight : 1; /* if negative or 0, use 1 */ + + timeLimit = parseInt($('#ida_section input[name=time_limit]').val()); + + // Any non-negative integer, indicates "forever". + timeLimit = (timeLimit <= 0 || isNaN(timeLimit)) ? -1 : timeLimit; + + finder = new PF.IDAStarFinder({ + timeLimit: timeLimit, + trackRecursion: trackRecursion, + allowDiagonal: allowDiagonal, + dontCrossCorners: dontCrossCorners, + heuristic: PF.Heuristic[heuristic], + weight: weight + }); + + break; + } + + return finder; + } +}; diff --git a/node_modules/pathfinding/visual/js/view.js b/node_modules/pathfinding/visual/js/view.js new file mode 100644 index 0000000..7560dda --- /dev/null +++ b/node_modules/pathfinding/visual/js/view.js @@ -0,0 +1,335 @@ +/** + * The pathfinding visualization. + * It uses raphael.js to show the grids. + */ +var View = { + nodeSize: 30, // width and height of a single node, in pixel + nodeStyle: { + normal: { + fill: 'white', + 'stroke-opacity': 0.2, // the border + }, + blocked: { + fill: 'grey', + 'stroke-opacity': 0.2, + }, + start: { + fill: '#0d0', + 'stroke-opacity': 0.2, + }, + end: { + fill: '#e40', + 'stroke-opacity': 0.2, + }, + opened: { + fill: '#98fb98', + 'stroke-opacity': 0.2, + }, + closed: { + fill: '#afeeee', + 'stroke-opacity': 0.2, + }, + failed: { + fill: '#ff8888', + 'stroke-opacity': 0.2, + }, + tested: { + fill: '#e5e5e5', + 'stroke-opacity': 0.2, + }, + }, + nodeColorizeEffect: { + duration: 50, + }, + nodeZoomEffect: { + duration: 200, + transform: 's1.2', // scale by 1.2x + transformBack: 's1.0', + }, + pathStyle: { + stroke: 'yellow', + 'stroke-width': 3, + }, + supportedOperations: ['opened', 'closed', 'tested'], + init: function(opts) { + this.numCols = opts.numCols; + this.numRows = opts.numRows; + this.paper = Raphael('draw_area'); + this.$stats = $('#stats'); + }, + /** + * Generate the grid asynchronously. + * This method will be a very expensive task. + * Therefore, in order to not to block the rendering of browser ui, + * I decomposed the task into smaller ones. Each will only generate a row. + */ + generateGrid: function(callback) { + var i, j, x, y, + rect, + normalStyle, nodeSize, + createRowTask, sleep, tasks, + nodeSize = this.nodeSize, + normalStyle = this.nodeStyle.normal, + numCols = this.numCols, + numRows = this.numRows, + paper = this.paper, + rects = this.rects = [], + $stats = this.$stats; + + paper.setSize(numCols * nodeSize, numRows * nodeSize); + + createRowTask = function(rowId) { + return function(done) { + rects[rowId] = []; + for (j = 0; j < numCols; ++j) { + x = j * nodeSize; + y = rowId * nodeSize; + + rect = paper.rect(x, y, nodeSize, nodeSize); + rect.attr(normalStyle); + rects[rowId].push(rect); + } + $stats.text( + 'generating grid ' + + Math.round((rowId + 1) / numRows * 100) + '%' + ); + done(null); + }; + }; + + sleep = function(done) { + setTimeout(function() { + done(null); + }, 0); + }; + + tasks = []; + for (i = 0; i < numRows; ++i) { + tasks.push(createRowTask(i)); + tasks.push(sleep); + } + + async.series(tasks, function() { + if (callback) { + callback(); + } + }); + }, + setStartPos: function(gridX, gridY) { + var coord = this.toPageCoordinate(gridX, gridY); + if (!this.startNode) { + this.startNode = this.paper.rect( + coord[0], + coord[1], + this.nodeSize, + this.nodeSize + ).attr(this.nodeStyle.normal) + .animate(this.nodeStyle.start, 1000); + } else { + this.startNode.attr({ x: coord[0], y: coord[1] }).toFront(); + } + }, + setEndPos: function(gridX, gridY) { + var coord = this.toPageCoordinate(gridX, gridY); + if (!this.endNode) { + this.endNode = this.paper.rect( + coord[0], + coord[1], + this.nodeSize, + this.nodeSize + ).attr(this.nodeStyle.normal) + .animate(this.nodeStyle.end, 1000); + } else { + this.endNode.attr({ x: coord[0], y: coord[1] }).toFront(); + } + }, + /** + * Set the attribute of the node at the given coordinate. + */ + setAttributeAt: function(gridX, gridY, attr, value) { + var color, nodeStyle = this.nodeStyle; + switch (attr) { + case 'walkable': + color = value ? nodeStyle.normal.fill : nodeStyle.blocked.fill; + this.setWalkableAt(gridX, gridY, value); + break; + case 'opened': + this.colorizeNode(this.rects[gridY][gridX], nodeStyle.opened.fill); + this.setCoordDirty(gridX, gridY, true); + break; + case 'closed': + this.colorizeNode(this.rects[gridY][gridX], nodeStyle.closed.fill); + this.setCoordDirty(gridX, gridY, true); + break; + case 'tested': + color = (value === true) ? nodeStyle.tested.fill : nodeStyle.normal.fill; + + this.colorizeNode(this.rects[gridY][gridX], color); + this.setCoordDirty(gridX, gridY, true); + break; + case 'parent': + // XXX: Maybe draw a line from this node to its parent? + // This would be expensive. + break; + default: + console.error('unsupported operation: ' + attr + ':' + value); + return; + } + }, + colorizeNode: function(node, color) { + node.animate({ + fill: color + }, this.nodeColorizeEffect.duration); + }, + zoomNode: function(node) { + node.toFront().attr({ + transform: this.nodeZoomEffect.transform, + }).animate({ + transform: this.nodeZoomEffect.transformBack, + }, this.nodeZoomEffect.duration); + }, + setWalkableAt: function(gridX, gridY, value) { + var node, i, blockedNodes = this.blockedNodes; + if (!blockedNodes) { + blockedNodes = this.blockedNodes = new Array(this.numRows); + for (i = 0; i < this.numRows; ++i) { + blockedNodes[i] = []; + } + } + node = blockedNodes[gridY][gridX]; + if (value) { + // clear blocked node + if (node) { + this.colorizeNode(node, this.rects[gridY][gridX].attr('fill')); + this.zoomNode(node); + setTimeout(function() { + node.remove(); + }, this.nodeZoomEffect.duration); + blockedNodes[gridY][gridX] = null; + } + } else { + // draw blocked node + if (node) { + return; + } + node = blockedNodes[gridY][gridX] = this.rects[gridY][gridX].clone(); + this.colorizeNode(node, this.nodeStyle.blocked.fill); + this.zoomNode(node); + } + }, + clearFootprints: function() { + var i, x, y, coord, coords = this.getDirtyCoords(); + for (i = 0; i < coords.length; ++i) { + coord = coords[i]; + x = coord[0]; + y = coord[1]; + this.rects[y][x].attr(this.nodeStyle.normal); + this.setCoordDirty(x, y, false); + } + }, + clearBlockedNodes: function() { + var i, j, blockedNodes = this.blockedNodes; + if (!blockedNodes) { + return; + } + for (i = 0; i < this.numRows; ++i) { + for (j = 0 ;j < this.numCols; ++j) { + if (blockedNodes[i][j]) { + blockedNodes[i][j].remove(); + blockedNodes[i][j] = null; + } + } + } + }, + drawPath: function(path) { + if (!path.length) { + return; + } + var svgPath = this.buildSvgPath(path); + this.path = this.paper.path(svgPath).attr(this.pathStyle); + }, + /** + * Given a path, build its SVG represention. + */ + buildSvgPath: function(path) { + var i, strs = [], size = this.nodeSize; + + strs.push('M' + (path[0][0] * size + size / 2) + ' ' + + (path[0][1] * size + size / 2)); + for (i = 1; i < path.length; ++i) { + strs.push('L' + (path[i][0] * size + size / 2) + ' ' + + (path[i][1] * size + size / 2)); + } + + return strs.join(''); + }, + clearPath: function() { + if (this.path) { + this.path.remove(); + } + }, + /** + * Helper function to convert the page coordinate to grid coordinate + */ + toGridCoordinate: function(pageX, pageY) { + return [ + Math.floor(pageX / this.nodeSize), + Math.floor(pageY / this.nodeSize) + ]; + }, + /** + * helper function to convert the grid coordinate to page coordinate + */ + toPageCoordinate: function(gridX, gridY) { + return [ + gridX * this.nodeSize, + gridY * this.nodeSize + ]; + }, + showStats: function(opts) { + var texts = [ + 'length: ' + Math.round(opts.pathLength * 100) / 100, + 'time: ' + opts.timeSpent + 'ms', + 'operations: ' + opts.operationCount + ]; + $('#stats').show().html(texts.join('
')); + }, + setCoordDirty: function(gridX, gridY, isDirty) { + var x, y, + numRows = this.numRows, + numCols = this.numCols, + coordDirty; + + if (this.coordDirty === undefined) { + coordDirty = this.coordDirty = []; + for (y = 0; y < numRows; ++y) { + coordDirty.push([]); + for (x = 0; x < numCols; ++x) { + coordDirty[y].push(false); + } + } + } + + this.coordDirty[gridY][gridX] = isDirty; + }, + getDirtyCoords: function() { + var x, y, + numRows = this.numRows, + numCols = this.numCols, + coordDirty = this.coordDirty, + coords = []; + + if (coordDirty === undefined) { + return []; + } + + for (y = 0; y < numRows; ++y) { + for (x = 0; x < numCols; ++x) { + if (coordDirty[y][x]) { + coords.push([x, y]); + } + } + } + return coords; + }, +}; diff --git a/node_modules/pathfinding/visual/lib/async.min.js b/node_modules/pathfinding/visual/lib/async.min.js new file mode 100644 index 0000000..53e457c --- /dev/null +++ b/node_modules/pathfinding/visual/lib/async.min.js @@ -0,0 +1 @@ +/*global setTimeout: false, console: false */(function(){var a={},b=this,c=b.async;typeof module!="undefined"&&module.exports?module.exports=a:b.async=a,a.noConflict=function(){return b.async=c,a};var d=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;cd?1:0};d(null,e(b.sort(c),function(a){return a.value}))})},a.auto=function(a,b){b=b||function(){};var c=g(a);if(!c.length)return b(null);var e={},h=[],i=function(a){h.unshift(a)},j=function(a){for(var b=0;b>>0;if("[object Function]"!=m(a))throw new TypeError; +for(;c>>0,e=Array(c);if("[object Function]"!=m(a))throw new TypeError;for(var g=0;g>>0,e=[];if("[object Function]"!=m(a))throw new TypeError;for(var g=0;g>>0;if("[object Function]"!=m(a))throw new TypeError;for(var e=0;e>>0;if("[object Function]"!=m(a))throw new TypeError;for(var e=0;e>>0;if("[object Function]"!=m(a))throw new TypeError; +if(!b&&1==arguments.length)throw new TypeError;var c=0,e;if(2<=arguments.length)e=arguments[1];else{do{if(c in d){e=d[c++];break}if(++c>=b)throw new TypeError;}while(1)}for(;c>>0;if("[object Function]"!=m(a))throw new TypeError;if(!b&&1==arguments.length)throw new TypeError;var c,b=b-1;if(2<=arguments.length)c=arguments[1];else{do{if(b in d){c=d[b--]; +break}if(0>--b)throw new TypeError;}while(1)}do b in this&&(c=a.call(void 0,c,d[b],b,d));while(b--);return c};if(!Array.prototype.indexOf)Array.prototype.indexOf=function(a){var d=i(this),b=d.length>>>0;if(!b)return-1;var c=0;1>>0;if(!b)return-1;var c=b-1;1c?"-":9999=c?-4:-6);for(d=a.length;d--;)b=a[d],10>b&&(a[d]="0"+b);return c+"-"+a.slice(0,2).join("-")+"T"+a.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};if(!Date.now)Date.now=function(){return(new Date).getTime()};if(!Date.prototype.toJSON)Date.prototype.toJSON=function(){if("function"!=typeof this.toISOString)throw new TypeError;return this.toISOString()}; +if(!Date.parse||864E13!==Date.parse("+275760-09-13T00:00:00.000Z"))Date=function(a){var d=function g(b,d,c,f,h,i,j){var k=arguments.length;return this instanceof a?(k=1==k&&""+b===b?new a(g.parse(b)):7<=k?new a(b,d,c,f,h,i,j):6<=k?new a(b,d,c,f,h,i):5<=k?new a(b,d,c,f,h):4<=k?new a(b,d,c,f):3<=k?new a(b,d,c):2<=k?new a(b,d):1<=k?new a(b):new a,k.constructor=g,k):a.apply(this,arguments)},b=RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$"), +c;for(c in a)d[c]=a[c];d.now=a.now;d.UTC=a.UTC;d.prototype=a.prototype;d.prototype.constructor=d;d.parse=function(d){var c=b.exec(d);if(c){c.shift();for(var f=1;7>f;f++)c[f]=+(c[f]||(3>f?1:0)),1==f&&c[f]--;var h=+c.pop(),i=+c.pop(),j=c.pop(),f=0;if(j){if(23=h?(c[0]=h+400,a.UTC.apply(this,c)+f-126227808E5):a.UTC.apply(this,c)+f}return a.parse.apply(this,arguments)};return d}(Date);j="\t\n\u000b\u000c\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff"; +if(!String.prototype.trim||j.trim()){j="["+j+"]";var A=RegExp("^"+j+j+"*"),B=RegExp(j+j+"*$");String.prototype.trim=function(){return(""+this).replace(A,"").replace(B,"")}}var v=function(a){a=+a;a!==a?a=0:0!==a&&a!==1/0&&a!==-(1/0)&&(a=(0").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( +a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f +.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[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","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/pathfinding-browser.min.js b/node_modules/pathfinding/visual/lib/pathfinding-browser.min.js new file mode 100644 index 0000000..76ec784 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/pathfinding-browser.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.PF=t()}}(function(){return function t(e,r,i){function n(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return n(r?r:t)},l,l.exports,t,e,r,i)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;st?-1:t>e?1:0},h=function(t,e,n,o,s){var a;if(null==n&&(n=0),null==s&&(s=r),0>n)throw new Error("lo must be non-negative");for(null==o&&(o=t.length);o>n;)a=i((n+o)/2),s(e,t[a])<0?o=a:n=a+1;return[].splice.apply(t,[n,n-n].concat(e)),e},s=function(t,e,i){return null==i&&(i=r),t.push(e),d(t,0,t.length-1,i)},o=function(t,e){var i,n;return null==e&&(e=r),i=t.pop(),t.length?(n=t[0],t[0]=i,g(t,0,e)):n=i,n},u=function(t,e,i){var n;return null==i&&(i=r),n=t[0],t[0]=e,g(t,0,i),n},a=function(t,e,i){var n;return null==i&&(i=r),t.length&&i(t[0],e)<0&&(n=[t[0],e],e=n[0],t[0]=n[1],g(t,0,i)),e},n=function(t,e){var n,o,s,a,u,h;for(null==e&&(e=r),a=function(){h=[];for(var e=0,r=i(t.length/2);r>=0?r>e:e>r;r>=0?e++:e--)h.push(e);return h}.apply(this).reverse(),u=[],o=0,s=a.length;s>o;o++)n=a[o],u.push(g(t,n,e));return u},f=function(t,e,i){var n;return null==i&&(i=r),n=t.indexOf(e),-1!==n?(d(t,0,n,i),g(t,n,i)):void 0},p=function(t,e,i){var o,s,u,h,l;if(null==i&&(i=r),s=t.slice(0,e),!s.length)return s;for(n(s,i),l=t.slice(e),u=0,h=l.length;h>u;u++)o=l[u],a(s,o,i);return s.sort(i).reverse()},c=function(t,e,i){var s,a,u,p,c,f,d,g,b,y;if(null==i&&(i=r),10*e<=t.length){if(p=t.slice(0,e).sort(i),!p.length)return p;for(u=p[p.length-1],g=t.slice(e),c=0,d=g.length;d>c;c++)s=g[c],i(s,u)<0&&(h(p,s,0,null,i),p.pop(),u=p[p.length-1]);return p}for(n(t,i),y=[],a=f=0,b=l(e,t.length);b>=0?b>f:f>b;a=b>=0?++f:--f)y.push(o(t,i));return y},d=function(t,e,i,n){var o,s,a;for(null==n&&(n=r),o=t[i];i>e&&(a=i-1>>1,s=t[a],n(o,s)<0);)t[i]=s,i=a;return t[i]=o},g=function(t,e,i){var n,o,s,a,u;for(null==i&&(i=r),o=t.length,u=e,s=t[e],n=2*e+1;o>n;)a=n+1,o>a&&!(i(t[n],t[a])<0)&&(n=a),t[e]=t[n],e=n,n=2*e+1;return t[e]=s,d(t,u,e,i)},t=function(){function t(t){this.cmp=null!=t?t:r,this.nodes=[]}return t.push=s,t.pop=o,t.replace=u,t.pushpop=a,t.heapify=n,t.nlargest=p,t.nsmallest=c,t.prototype.push=function(t){return s(this.nodes,t,this.cmp)},t.prototype.pop=function(){return o(this.nodes,this.cmp)},t.prototype.peek=function(){return this.nodes[0]},t.prototype.contains=function(t){return-1!==this.nodes.indexOf(t)},t.prototype.replace=function(t){return u(this.nodes,t,this.cmp)},t.prototype.pushpop=function(t){return a(this.nodes,t,this.cmp)},t.prototype.heapify=function(){return n(this.nodes,this.cmp)},t.prototype.updateItem=function(t){return f(this.nodes,t,this.cmp)},t.prototype.clear=function(){return this.nodes=[]},t.prototype.empty=function(){return 0===this.nodes.length},t.prototype.size=function(){return this.nodes.length},t.prototype.clone=function(){var e;return e=new t,e.nodes=this.nodes.slice(0),e},t.prototype.toArray=function(){return this.nodes.slice(0)},t.prototype.insert=t.prototype.push,t.prototype.remove=t.prototype.pop,t.prototype.top=t.prototype.peek,t.prototype.front=t.prototype.peek,t.prototype.has=t.prototype.contains,t.prototype.copy=t.prototype.clone,t}(),("undefined"!=typeof e&&null!==e?e.exports:void 0)?e.exports=t:window.Heap=t}.call(this)},{}],3:[function(t,e){function r(t,e,r){this.width=t,this.height=e,this.nodes=this._buildNodes(t,e,r)}var i=t("./Node");r.prototype._buildNodes=function(t,e,r){var n,o,s=new Array(e);for(n=0;e>n;++n)for(s[n]=new Array(t),o=0;t>o;++o)s[n][o]=new i(o,n);if(void 0===r)return s;if(r.length!==e||r[0].length!==t)throw new Error("Matrix size does not fit");for(n=0;e>n;++n)for(o=0;t>o;++o)r[n][o]&&(s[n][o].walkable=!1);return s},r.prototype.getNodeAt=function(t,e){return this.nodes[e][t]},r.prototype.isWalkableAt=function(t,e){return this.isInside(t,e)&&this.nodes[e][t].walkable},r.prototype.isInside=function(t,e){return t>=0&&t=0&&et;++t)for(u[t]=new Array(n),e=0;n>e;++e)u[t][e]=new i(e,t,s[t][e].walkable);return a.nodes=u,a},e.exports=r},{"./Node":5}],4:[function(t,e){e.exports={manhattan:function(t,e){return t+e},euclidean:function(t,e){return Math.sqrt(t*t+e*e)},octile:function(t,e){var r=Math.SQRT2-1;return e>t?r*t+e:r*e+t},chebyshev:function(t,e){return Math.max(t,e)}}},{}],5:[function(t,e){function r(t,e,r){this.x=t,this.y=e,this.walkable=void 0===r?!0:r}e.exports=r},{}],6:[function(t,e,r){function i(t){for(var e=[[t.x,t.y]];t.parent;)t=t.parent,e.push([t.x,t.y]);return e.reverse()}function n(t,e){var r=i(t),n=i(e);return r.concat(n.reverse())}function o(t){var e,r,i,n,o,s=0;for(e=1;et?1:-1,o=i>e?1:-1,u=s-a;;){if(p.push([t,e]),t===r&&e===i)break;h=2*u,h>-a&&(u-=a,t+=n),s>h&&(u+=s,e+=o)}return p}function a(t){var e,r,i,n,o,a,u=[],h=t.length;if(2>h)return u;for(o=0;h-1>o;++o)for(e=t[o],r=t[o+1],i=s(e[0],e[1],r[0],r[1]),n=i.length,a=0;n-1>a;++a)u.push(i[a]);return u.push(t[h-1]),u}function u(t,e){var r,i,n,o,a,u,h,l,p,c,f,d=e.length,g=e[0][0],b=e[0][1],y=e[d-1][0],A=e[d-1][1];for(r=g,i=b,a=[[r,i]],u=2;d>u;++u){for(l=e[u],n=l[0],o=l[1],p=s(r,i,n,o),f=!1,h=1;hl;++l)h=u[l],h.closed||(c=h.x,f=h.y,d=a.g+(0===c-a.x||0===f-a.y?1:x),(!h.opened||dl;++l)if(h=u[l],!h.closed){if(h.opened===C)return n.biBacktrace(a,h);c=h.x,f=h.y,d=a.g+(0===c-a.x||0===f-a.y?1:W),(!h.opened||dl;++l)if(h=u[l],!h.closed){if(h.opened===N)return n.biBacktrace(h,a);c=h.x,f=h.y,d=a.g+(0===c-a.x||0===f-a.y?1:W),(!h.opened||dh;++h)if(a=s[h],!a.closed)if(a.opened){if(a.by===A)return i.biBacktrace(u,a)}else f.push(a),a.parent=u,a.opened=!0,a.by=y;for(u=d.shift(),u.closed=!0,s=o.getNeighbors(u,g,b),h=0,l=s.length;l>h;++h)if(a=s[h],!a.closed)if(a.opened){if(a.by===y)return i.biBacktrace(a,u)}else d.push(a),a.parent=u,a.opened=!0,a.by=A}return[]},e.exports=r},{"../core/Util":6}],12:[function(t,e){function r(t){i.call(this,t),this.heuristic=function(){return 0}}var i=t("./BiAStarFinder");r.prototype=new i,r.prototype.constructor=r,e.exports=r},{"./BiAStarFinder":9}],13:[function(t,e){function r(t){t=t||{},this.allowDiagonal=t.allowDiagonal,this.dontCrossCorners=t.dontCrossCorners}var i=t("../core/Util");r.prototype.findPath=function(t,e,r,n,o){var s,a,u,h,l,p=[],c=this.allowDiagonal,f=this.dontCrossCorners,d=o.getNodeAt(t,e),g=o.getNodeAt(r,n);for(p.push(d),d.opened=!0;p.length;){if(u=p.shift(),u.closed=!0,u===g)return i.backtrace(g);for(s=o.getNeighbors(u,c,f),h=0,l=s.length;l>h;++h)a=s[h],a.closed||a.opened||(p.push(a),a.opened=!0,a.parent=u)}return[]},e.exports=r},{"../core/Util":6}],14:[function(t,e){function r(t){i.call(this,t),this.heuristic=function(){return 0}}var i=t("./AStarFinder");r.prototype=new i,r.prototype.constructor=r,e.exports=r},{"./AStarFinder":7}],15:[function(t,e){function r(t){t=t||{},this.allowDiagonal=t.allowDiagonal,this.dontCrossCorners=t.dontCrossCorners,this.heuristic=t.heuristic||i.manhattan,this.weight=t.weight||1,this.trackRecursion=t.trackRecursion||!1,this.timeLimit=t.timeLimit||1/0}t("../core/Util");var i=t("../core/Heuristic"),n=t("../core/Node");r.prototype.findPath=function(t,e,r,i,o){var s,a,u,h=0,l=(new Date).getTime(),p=function(t,e){return this.heuristic(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}.bind(this),c=function(t,e){return t.x===e.x||t.y===e.y?1:Math.SQRT2},f=function(t,e,r,i,s){if(h++,this.timeLimit>0&&(new Date).getTime()-l>1e3*this.timeLimit)return 1/0;var a=e+p(t,g)*this.weight;if(a>r)return a;if(t==g)return i[s]=[t.x,t.y],t;var u,d,b,y,A=o.getNeighbors(t,this.allowDiagonal,this.dontCrossCorners);for(b=0,u=1/0;y=A[b];++b){if(this.trackRecursion&&(y.retainCount=y.retainCount+1||1,y.tested!==!0&&(y.tested=!0)),d=f(y,e+c(t,y),r,i,s+1),d instanceof n)return i[s]=[t.x,t.y],d;this.trackRecursion&&0===--y.retainCount&&(y.tested=!1),u>d&&(u=d)}return u}.bind(this),d=o.getNodeAt(t,e),g=o.getNodeAt(r,i),b=p(d,g);for(s=0;!0;++s){if(a=[],u=f(d,0,b,a,0),1/0===u)return[];if(u instanceof n)return a;b=u}return[]},e.exports=r},{"../core/Heuristic":4,"../core/Node":5,"../core/Util":6}],16:[function(t,e){function r(t){t=t||{},this.heuristic=t.heuristic||o.manhattan,this.trackJumpRecursion=t.trackJumpRecursion||!1}var i=t("heap"),n=t("../core/Util"),o=t("../core/Heuristic");r.prototype.findPath=function(t,e,r,o,s){var a,u=this.openList=new i(function(t,e){return t.f-e.f}),h=this.startNode=s.getNodeAt(t,e),l=this.endNode=s.getNodeAt(r,o);for(this.grid=s,h.g=0,h.f=0,u.push(h),h.opened=!0;!u.empty();){if(a=u.pop(),a.closed=!0,a===l)return n.expandPath(n.backtrace(l));this._identifySuccessors(a)}return[]},r.prototype._identifySuccessors=function(t){var e,r,i,n,s,a,u,h,l,p,c=this.grid,f=this.heuristic,d=this.openList,g=this.endNode.x,b=this.endNode.y,y=t.x,A=t.y,k=Math.abs;for(Math.max,e=this._findNeighbors(t),n=0,s=e.length;s>n;++n)if(r=e[n],i=this._jump(r[0],r[1],y,A)){if(a=i[0],u=i[1],p=c.getNodeAt(a,u),p.closed)continue;h=o.octile(k(a-y),k(u-A)),l=t.g+h,(!p.opened||la;++a)s=o[a],f.push([s.x,s.y]);return f},e.exports=r},{"../core/Heuristic":4,"../core/Util":6,heap:1}],17:[function(t,e){function r(t){n.call(this,t),t=t||{},this.heuristic=t.heuristic||i.manhattan}var i=t("../core/Heuristic"),n=t("./JumpPointFinder");r.prototype=new n,r.prototype.constructor=r,r.prototype._jump=function(t,e,r,i){var n=this.grid,o=t-r,s=e-i;if(!n.isWalkableAt(t,e))return null;if(this.trackJumpRecursion===!0&&(n.getNodeAt(t,e).tested=!0),n.getNodeAt(t,e)===this.endNode)return[t,e];if(0!==o){if(n.isWalkableAt(t,e-1)&&!n.isWalkableAt(t-o,e-1)||n.isWalkableAt(t,e+1)&&!n.isWalkableAt(t-o,e+1))return[t,e]}else{if(0===s)throw new Error("Only horizontal and vertical movements are allowed");if(n.isWalkableAt(t-1,e)&&!n.isWalkableAt(t-1,e-s)||n.isWalkableAt(t+1,e)&&!n.isWalkableAt(t+1,e-s))return[t,e];if(this._jump(t+1,e,t,e)||this._jump(t-1,e,t,e))return[t,e]}return this._jump(t+o,e+s,t,e)},r.prototype._findNeighbors=function(t){var e,r,i,n,o,s,a,u,h=t.parent,l=t.x,p=t.y,c=this.grid,f=[];if(h)e=h.x,r=h.y,i=(l-e)/Math.max(Math.abs(l-e),1),n=(p-r)/Math.max(Math.abs(p-r),1),0!==i?(c.isWalkableAt(l,p-1)&&f.push([l,p-1]),c.isWalkableAt(l,p+1)&&f.push([l,p+1]),c.isWalkableAt(l+i,p)&&f.push([l+i,p])):0!==n&&(c.isWalkableAt(l-1,p)&&f.push([l-1,p]),c.isWalkableAt(l+1,p)&&f.push([l+1,p]),c.isWalkableAt(l,p+n)&&f.push([l,p+n]));else for(o=c.getNeighbors(t,!1),a=0,u=o.length;u>a;++a)s=o[a],f.push([s.x,s.y]);return f},e.exports=r},{"../core/Heuristic":4,"./JumpPointFinder":16}],18:[function(t,e){e.exports={Heap:t("heap"),Node:t("./core/Node"),Grid:t("./core/Grid"),Util:t("./core/Util"),Heuristic:t("./core/Heuristic"),AStarFinder:t("./finders/AStarFinder"),BestFirstFinder:t("./finders/BestFirstFinder"),BreadthFirstFinder:t("./finders/BreadthFirstFinder"),DijkstraFinder:t("./finders/DijkstraFinder"),BiAStarFinder:t("./finders/BiAStarFinder"),BiBestFirstFinder:t("./finders/BiBestFirstFinder"),BiBreadthFirstFinder:t("./finders/BiBreadthFirstFinder"),BiDijkstraFinder:t("./finders/BiDijkstraFinder"),IDAStarFinder:t("./finders/IDAStarFinder"),JumpPointFinder:t("./finders/JumpPointFinder"),OrthogonalJumpPointFinder:t("./finders/OrthogonalJumpPointFinder")}},{"./core/Grid":3,"./core/Heuristic":4,"./core/Node":5,"./core/Util":6,"./finders/AStarFinder":7,"./finders/BestFirstFinder":8,"./finders/BiAStarFinder":9,"./finders/BiBestFirstFinder":10,"./finders/BiBreadthFirstFinder":11,"./finders/BiDijkstraFinder":12,"./finders/BreadthFirstFinder":13,"./finders/DijkstraFinder":14,"./finders/IDAStarFinder":15,"./finders/JumpPointFinder":16,"./finders/OrthogonalJumpPointFinder":17,heap:1}]},{},[18])(18)}); \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/raphael-min.js b/node_modules/pathfinding/visual/lib/raphael-min.js new file mode 100644 index 0000000..ed99de2 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/raphael-min.js @@ -0,0 +1,10 @@ +// ┌────────────────────────────────────────────────────────────────────┐ \\ +// │ Raphaël 2.1.0 - JavaScript Vector Library │ \\ +// ├────────────────────────────────────────────────────────────────────┤ \\ +// │ Copyright © 2008-2012 Dmitry Baranovskiy (http://raphaeljs.com) │ \\ +// │ Copyright © 2008-2012 Sencha Labs (http://sencha.com) │ \\ +// ├────────────────────────────────────────────────────────────────────┤ \\ +// │ Licensed under the MIT (http://raphaeljs.com/license.html) license.│ \\ +// └────────────────────────────────────────────────────────────────────┘ \\ + +(function(a){var b="0.3.4",c="hasOwnProperty",d=/[\.\/]/,e="*",f=function(){},g=function(a,b){return a-b},h,i,j={n:{}},k=function(a,b){var c=j,d=i,e=Array.prototype.slice.call(arguments,2),f=k.listeners(a),l=0,m=!1,n,o=[],p={},q=[],r=h,s=[];h=a,i=0;for(var t=0,u=f.length;tf*b.top){e=b.percents[y],p=b.percents[y-1]||0,t=t/b.top*(e-p),o=b.percents[y+1],j=b.anim[e];break}f&&d.attr(b.anim[b.percents[y]])}if(!!j){if(!k){for(var A in j)if(j[g](A))if(U[g](A)||d.paper.customAttributes[g](A)){u[A]=d.attr(A),u[A]==null&&(u[A]=T[A]),v[A]=j[A];switch(U[A]){case C:w[A]=(v[A]-u[A])/t;break;case"colour":u[A]=a.getRGB(u[A]);var B=a.getRGB(v[A]);w[A]={r:(B.r-u[A].r)/t,g:(B.g-u[A].g)/t,b:(B.b-u[A].b)/t};break;case"path":var D=bR(u[A],v[A]),E=D[1];u[A]=D[0],w[A]=[];for(y=0,z=u[A].length;yd)return d;while(cf?c=e:d=e,e=(d-c)/2+c}return e}function n(a,b){var c=o(a,b);return((l*c+k)*c+j)*c}function m(a){return((i*a+h)*a+g)*a}var g=3*b,h=3*(d-b)-g,i=1-g-h,j=3*c,k=3*(e-c)-j,l=1-j-k;return n(a,1/(200*f))}function cq(){return this.x+q+this.y+q+this.width+" × "+this.height}function cp(){return this.x+q+this.y}function cb(a,b,c,d,e,f){a!=null?(this.a=+a,this.b=+b,this.c=+c,this.d=+d,this.e=+e,this.f=+f):(this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0)}function bH(b,c,d){b=a._path2curve(b),c=a._path2curve(c);var e,f,g,h,i,j,k,l,m,n,o=d?0:[];for(var p=0,q=b.length;p=0&&y<=1&&A>=0&&A<=1&&(d?n++:n.push({x:x.x,y:x.y,t1:y,t2:A}))}}return n}function bF(a,b){return bG(a,b,1)}function bE(a,b){return bG(a,b)}function bD(a,b,c,d,e,f,g,h){if(!(x(a,c)x(e,g)||x(b,d)x(f,h))){var i=(a*d-b*c)*(e-g)-(a-c)*(e*h-f*g),j=(a*d-b*c)*(f-h)-(b-d)*(e*h-f*g),k=(a-c)*(f-h)-(b-d)*(e-g);if(!k)return;var l=i/k,m=j/k,n=+l.toFixed(2),o=+m.toFixed(2);if(n<+y(a,c).toFixed(2)||n>+x(a,c).toFixed(2)||n<+y(e,g).toFixed(2)||n>+x(e,g).toFixed(2)||o<+y(b,d).toFixed(2)||o>+x(b,d).toFixed(2)||o<+y(f,h).toFixed(2)||o>+x(f,h).toFixed(2))return;return{x:l,y:m}}}function bC(a,b,c,d,e,f,g,h,i){if(!(i<0||bB(a,b,c,d,e,f,g,h)n)k/=2,l+=(m1?1:i<0?0:i;var j=i/2,k=12,l=[-0.1252,.1252,-0.3678,.3678,-0.5873,.5873,-0.7699,.7699,-0.9041,.9041,-0.9816,.9816],m=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],n=0;for(var o=0;od;d+=2){var f=[{x:+a[d-2],y:+a[d-1]},{x:+a[d],y:+a[d+1]},{x:+a[d+2],y:+a[d+3]},{x:+a[d+4],y:+a[d+5]}];b?d?e-4==d?f[3]={x:+a[0],y:+a[1]}:e-2==d&&(f[2]={x:+a[0],y:+a[1]},f[3]={x:+a[2],y:+a[3]}):f[0]={x:+a[e-2],y:+a[e-1]}:e-4==d?f[3]=f[2]:d||(f[0]={x:+a[d],y:+a[d+1]}),c.push(["C",(-f[0].x+6*f[1].x+f[2].x)/6,(-f[0].y+6*f[1].y+f[2].y)/6,(f[1].x+6*f[2].x-f[3].x)/6,(f[1].y+6*f[2].y-f[3].y)/6,f[2].x,f[2].y])}return c}function bx(){return this.hex}function bv(a,b,c){function d(){var e=Array.prototype.slice.call(arguments,0),f=e.join("␀"),h=d.cache=d.cache||{},i=d.count=d.count||[];if(h[g](f)){bu(i,f);return c?c(h[f]):h[f]}i.length>=1e3&&delete h[i.shift()],i.push(f),h[f]=a[m](b,e);return c?c(h[f]):h[f]}return d}function bu(a,b){for(var c=0,d=a.length;c',bl=bk.firstChild,bl.style.behavior="url(#default#VML)";if(!bl||typeof bl.adj!="object")return a.type=p;bk=null}a.svg=!(a.vml=a.type=="VML"),a._Paper=j,a.fn=k=j.prototype=a.prototype,a._id=0,a._oid=0,a.is=function(a,b){b=v.call(b);if(b=="finite")return!M[g](+a);if(b=="array")return a instanceof Array;return b=="null"&&a===null||b==typeof a&&a!==null||b=="object"&&a===Object(a)||b=="array"&&Array.isArray&&Array.isArray(a)||H.call(a).slice(8,-1).toLowerCase()==b},a.angle=function(b,c,d,e,f,g){if(f==null){var h=b-d,i=c-e;if(!h&&!i)return 0;return(180+w.atan2(-i,-h)*180/B+360)%360}return a.angle(b,c,f,g)-a.angle(d,e,f,g)},a.rad=function(a){return a%360*B/180},a.deg=function(a){return a*180/B%360},a.snapTo=function(b,c,d){d=a.is(d,"finite")?d:10;if(a.is(b,E)){var e=b.length;while(e--)if(z(b[e]-c)<=d)return b[e]}else{b=+b;var f=c%b;if(fb-d)return c-f+b}return c};var bn=a.createUUID=function(a,b){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a,b).toUpperCase()}}(/[xy]/g,function(a){var b=w.random()*16|0,c=a=="x"?b:b&3|8;return c.toString(16)});a.setWindow=function(b){eve("raphael.setWindow",a,h.win,b),h.win=b,h.doc=h.win.document,a._engine.initWin&&a._engine.initWin(h.win)};var bo=function(b){if(a.vml){var c=/^\s+|\s+$/g,d;try{var e=new ActiveXObject("htmlfile");e.write(""),e.close(),d=e.body}catch(f){d=createPopup().document.body}var g=d.createTextRange();bo=bv(function(a){try{d.style.color=r(a).replace(c,p);var b=g.queryCommandValue("ForeColor");b=(b&255)<<16|b&65280|(b&16711680)>>>16;return"#"+("000000"+b.toString(16)).slice(-6)}catch(e){return"none"}})}else{var i=h.doc.createElement("i");i.title="Raphaël Colour Picker",i.style.display="none",h.doc.body.appendChild(i),bo=bv(function(a){i.style.color=a;return h.doc.defaultView.getComputedStyle(i,p).getPropertyValue("color")})}return bo(b)},bp=function(){return"hsb("+[this.h,this.s,this.b]+")"},bq=function(){return"hsl("+[this.h,this.s,this.l]+")"},br=function(){return this.hex},bs=function(b,c,d){c==null&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b&&(d=b.b,c=b.g,b=b.r);if(c==null&&a.is(b,D)){var e=a.getRGB(b);b=e.r,c=e.g,d=e.b}if(b>1||c>1||d>1)b/=255,c/=255,d/=255;return[b,c,d]},bt=function(b,c,d,e){b*=255,c*=255,d*=255;var f={r:b,g:c,b:d,hex:a.rgb(b,c,d),toString:br};a.is(e,"finite")&&(f.opacity=e);return f};a.color=function(b){var c;a.is(b,"object")&&"h"in b&&"s"in b&&"b"in b?(c=a.hsb2rgb(b),b.r=c.r,b.g=c.g,b.b=c.b,b.hex=c.hex):a.is(b,"object")&&"h"in b&&"s"in b&&"l"in b?(c=a.hsl2rgb(b),b.r=c.r,b.g=c.g,b.b=c.b,b.hex=c.hex):(a.is(b,"string")&&(b=a.getRGB(b)),a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b?(c=a.rgb2hsl(b),b.h=c.h,b.s=c.s,b.l=c.l,c=a.rgb2hsb(b),b.v=c.b):(b={hex:"none"},b.r=b.g=b.b=b.h=b.s=b.v=b.l=-1)),b.toString=br;return b},a.hsb2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"b"in a&&(c=a.b,b=a.s,a=a.h,d=a.o),a*=360;var e,f,g,h,i;a=a%360/60,i=c*b,h=i*(1-z(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a];return bt(e,f,g,d)},a.hsl2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"l"in a&&(c=a.l,b=a.s,a=a.h);if(a>1||b>1||c>1)a/=360,b/=100,c/=100;a*=360;var e,f,g,h,i;a=a%360/60,i=2*b*(c<.5?c:1-c),h=i*(1-z(a%2-1)),e=f=g=c-i/2,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a];return bt(e,f,g,d)},a.rgb2hsb=function(a,b,c){c=bs(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g;f=x(a,b,c),g=f-y(a,b,c),d=g==0?null:f==a?(b-c)/g:f==b?(c-a)/g+2:(a-b)/g+4,d=(d+360)%6*60/360,e=g==0?0:g/f;return{h:d,s:e,b:f,toString:bp}},a.rgb2hsl=function(a,b,c){c=bs(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g,h,i;g=x(a,b,c),h=y(a,b,c),i=g-h,d=i==0?null:g==a?(b-c)/i:g==b?(c-a)/i+2:(a-b)/i+4,d=(d+360)%6*60/360,f=(g+h)/2,e=i==0?0:f<.5?i/(2*f):i/(2-2*f);return{h:d,s:e,l:f,toString:bq}},a._path2string=function(){return this.join(",").replace(Y,"$1")};var bw=a._preload=function(a,b){var c=h.doc.createElement("img");c.style.cssText="position:absolute;left:-9999em;top:-9999em",c.onload=function(){b.call(this),this.onload=null,h.doc.body.removeChild(this)},c.onerror=function(){h.doc.body.removeChild(this)},h.doc.body.appendChild(c),c.src=a};a.getRGB=bv(function(b){if(!b||!!((b=r(b)).indexOf("-")+1))return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:bx};if(b=="none")return{r:-1,g:-1,b:-1,hex:"none",toString:bx};!X[g](b.toLowerCase().substring(0,2))&&b.charAt()!="#"&&(b=bo(b));var c,d,e,f,h,i,j,k=b.match(L);if(k){k[2]&&(f=R(k[2].substring(5),16),e=R(k[2].substring(3,5),16),d=R(k[2].substring(1,3),16)),k[3]&&(f=R((i=k[3].charAt(3))+i,16),e=R((i=k[3].charAt(2))+i,16),d=R((i=k[3].charAt(1))+i,16)),k[4]&&(j=k[4][s](W),d=Q(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=Q(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),f=Q(j[2]),j[2].slice(-1)=="%"&&(f*=2.55),k[1].toLowerCase().slice(0,4)=="rgba"&&(h=Q(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100));if(k[5]){j=k[5][s](W),d=Q(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=Q(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),f=Q(j[2]),j[2].slice(-1)=="%"&&(f*=2.55),(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360),k[1].toLowerCase().slice(0,4)=="hsba"&&(h=Q(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsb2rgb(d,e,f,h)}if(k[6]){j=k[6][s](W),d=Q(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=Q(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),f=Q(j[2]),j[2].slice(-1)=="%"&&(f*=2.55),(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360),k[1].toLowerCase().slice(0,4)=="hsla"&&(h=Q(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsl2rgb(d,e,f,h)}k={r:d,g:e,b:f,toString:bx},k.hex="#"+(16777216|f|e<<8|d<<16).toString(16).slice(1),a.is(h,"finite")&&(k.opacity=h);return k}return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:bx}},a),a.hsb=bv(function(b,c,d){return a.hsb2rgb(b,c,d).hex}),a.hsl=bv(function(b,c,d){return a.hsl2rgb(b,c,d).hex}),a.rgb=bv(function(a,b,c){return"#"+(16777216|c|b<<8|a<<16).toString(16).slice(1)}),a.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||.75},c=this.hsb2rgb(b.h,b.s,b.b);b.h+=.075,b.h>1&&(b.h=0,b.s-=.2,b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b}));return c.hex},a.getColor.reset=function(){delete this.start},a.parsePathString=function(b){if(!b)return null;var c=bz(b);if(c.arr)return bJ(c.arr);var d={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},e=[];a.is(b,E)&&a.is(b[0],E)&&(e=bJ(b)),e.length||r(b).replace(Z,function(a,b,c){var f=[],g=b.toLowerCase();c.replace(_,function(a,b){b&&f.push(+b)}),g=="m"&&f.length>2&&(e.push([b][n](f.splice(0,2))),g="l",b=b=="m"?"l":"L");if(g=="r")e.push([b][n](f));else while(f.length>=d[g]){e.push([b][n](f.splice(0,d[g])));if(!d[g])break}}),e.toString=a._path2string,c.arr=bJ(e);return e},a.parseTransformString=bv(function(b){if(!b)return null;var c={r:3,s:4,t:2,m:6},d=[];a.is(b,E)&&a.is(b[0],E)&&(d=bJ(b)),d.length||r(b).replace($,function(a,b,c){var e=[],f=v.call(b);c.replace(_,function(a,b){b&&e.push(+b)}),d.push([b][n](e))}),d.toString=a._path2string;return d});var bz=function(a){var b=bz.ps=bz.ps||{};b[a]?b[a].sleep=100:b[a]={sleep:100},setTimeout(function(){for(var c in b)b[g](c)&&c!=a&&(b[c].sleep--,!b[c].sleep&&delete b[c])});return b[a]};a.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=A(j,3),l=A(j,2),m=i*i,n=m*i,o=k*a+l*3*i*c+j*3*i*i*e+n*g,p=k*b+l*3*i*d+j*3*i*i*f+n*h,q=a+2*i*(c-a)+m*(e-2*c+a),r=b+2*i*(d-b)+m*(f-2*d+b),s=c+2*i*(e-c)+m*(g-2*e+c),t=d+2*i*(f-d)+m*(h-2*f+d),u=j*a+i*c,v=j*b+i*d,x=j*e+i*g,y=j*f+i*h,z=90-w.atan2(q-s,r-t)*180/B;(q>s||r=a.x&&b<=a.x2&&c>=a.y&&c<=a.y2},a.isBBoxIntersect=function(b,c){var d=a.isPointInsideBBox;return d(c,b.x,b.y)||d(c,b.x2,b.y)||d(c,b.x,b.y2)||d(c,b.x2,b.y2)||d(b,c.x,c.y)||d(b,c.x2,c.y)||d(b,c.x,c.y2)||d(b,c.x2,c.y2)||(b.xc.x||c.xb.x)&&(b.yc.y||c.yb.y)},a.pathIntersection=function(a,b){return bH(a,b)},a.pathIntersectionNumber=function(a,b){return bH(a,b,1)},a.isPointInsidePath=function(b,c,d){var e=a.pathBBox(b);return a.isPointInsideBBox(e,c,d)&&bH(b,[["M",c,d],["H",e.x2+10]],1)%2==1},a._removedFactory=function(a){return function(){eve("raphael.log",null,"Raphaël: you are calling to method “"+a+"” of removed object",a)}};var bI=a.pathBBox=function(a){var b=bz(a);if(b.bbox)return b.bbox;if(!a)return{x:0,y:0,width:0,height:0,x2:0,y2:0};a=bR(a);var c=0,d=0,e=[],f=[],g;for(var h=0,i=a.length;h1&&(v=w.sqrt(v),c=v*c,d=v*d);var x=c*c,y=d*d,A=(f==g?-1:1)*w.sqrt(z((x*y-x*u*u-y*t*t)/(x*u*u+y*t*t))),C=A*c*u/d+(a+h)/2,D=A*-d*t/c+(b+i)/2,E=w.asin(((b-D)/d).toFixed(9)),F=w.asin(((i-D)/d).toFixed(9));E=aF&&(E=E-B*2),!g&&F>E&&(F=F-B*2)}else E=j[0],F=j[1],C=j[2],D=j[3];var G=F-E;if(z(G)>k){var H=F,I=h,J=i;F=E+k*(g&&F>E?1:-1),h=C+c*w.cos(F),i=D+d*w.sin(F),m=bO(h,i,c,d,e,0,g,I,J,[F,H,C,D])}G=F-E;var K=w.cos(E),L=w.sin(E),M=w.cos(F),N=w.sin(F),O=w.tan(G/4),P=4/3*c*O,Q=4/3*d*O,R=[a,b],S=[a+P*L,b-Q*K],T=[h+P*N,i-Q*M],U=[h,i];S[0]=2*R[0]-S[0],S[1]=2*R[1]-S[1];if(j)return[S,T,U][n](m);m=[S,T,U][n](m).join()[s](",");var V=[];for(var W=0,X=m.length;W"1e12"&&(l=.5),z(n)>"1e12"&&(n=.5),l>0&&l<1&&(q=bP(a,b,c,d,e,f,g,h,l),p.push(q.x),o.push(q.y)),n>0&&n<1&&(q=bP(a,b,c,d,e,f,g,h,n),p.push(q.x),o.push(q.y)),i=f-2*d+b-(h-2*f+d),j=2*(d-b)-2*(f-d),k=b-d,l=(-j+w.sqrt(j*j-4*i*k))/2/i,n=(-j-w.sqrt(j*j-4*i*k))/2/i,z(l)>"1e12"&&(l=.5),z(n)>"1e12"&&(n=.5),l>0&&l<1&&(q=bP(a,b,c,d,e,f,g,h,l),p.push(q.x),o.push(q.y)),n>0&&n<1&&(q=bP(a,b,c,d,e,f,g,h,n),p.push(q.x),o.push(q.y));return{min:{x:y[m](0,p),y:y[m](0,o)},max:{x:x[m](0,p),y:x[m](0,o)}}}),bR=a._path2curve=bv(function(a,b){var c=!b&&bz(a);if(!b&&c.curve)return bJ(c.curve);var d=bL(a),e=b&&bL(b),f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},h=function(a,b){var c,d;if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];!(a[0]in{T:1,Q:1})&&(b.qx=b.qy=null);switch(a[0]){case"M":b.X=a[1],b.Y=a[2];break;case"A":a=["C"][n](bO[m](0,[b.x,b.y][n](a.slice(1))));break;case"S":c=b.x+(b.x-(b.bx||b.x)),d=b.y+(b.y-(b.by||b.y)),a=["C",c,d][n](a.slice(1));break;case"T":b.qx=b.x+(b.x-(b.qx||b.x)),b.qy=b.y+(b.y-(b.qy||b.y)),a=["C"][n](bN(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1],b.qy=a[2],a=["C"][n](bN(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][n](bM(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][n](bM(b.x,b.y,a[1],b.y));break;case"V":a=["C"][n](bM(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][n](bM(b.x,b.y,b.X,b.Y))}return a},i=function(a,b){if(a[b].length>7){a[b].shift();var c=a[b];while(c.length)a.splice(b++,0,["C"][n](c.splice(0,6)));a.splice(b,1),l=x(d.length,e&&e.length||0)}},j=function(a,b,c,f,g){a&&b&&a[g][0]=="M"&&b[g][0]!="M"&&(b.splice(g,0,["M",f.x,f.y]),c.bx=0,c.by=0,c.x=a[g][1],c.y=a[g][2],l=x(d.length,e&&e.length||0))};for(var k=0,l=x(d.length,e&&e.length||0);ke){if(c&&!l.start){m=cs(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),k+=["C"+m.start.x,m.start.y,m.m.x,m.m.y,m.x,m.y];if(f)return k;l.start=k,k=["M"+m.x,m.y+"C"+m.n.x,m.n.y,m.end.x,m.end.y,i[5],i[6]].join(),n+=j,g=+i[5],h=+i[6];continue}if(!b&&!c){m=cs(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n);return{x:m.x,y:m.y,alpha:m.alpha}}}n+=j,g=+i[5],h=+i[6]}k+=i.shift()+i}l.end=k,m=b?n:c?l:a.findDotsAtSegment(g,h,i[0],i[1],i[2],i[3],i[4],i[5],1),m.alpha&&(m={x:m.x,y:m.y,alpha:m.alpha});return m}},cu=ct(1),cv=ct(),cw=ct(0,1);a.getTotalLength=cu,a.getPointAtLength=cv,a.getSubpath=function(a,b,c){if(this.getTotalLength(a)-c<1e-6)return cw(a,b).end;var d=cw(a,c,1);return b?cw(d,b).end:d},cl.getTotalLength=function(){if(this.type=="path"){if(this.node.getTotalLength)return this.node.getTotalLength();return cu(this.attrs.path)}},cl.getPointAtLength=function(a){if(this.type=="path")return cv(this.attrs.path,a)},cl.getSubpath=function(b,c){if(this.type=="path")return a.getSubpath(this.attrs.path,b,c)};var cx=a.easing_formulas={linear:function(a){return a},"<":function(a){return A(a,1.7)},">":function(a){return A(a,.48)},"<>":function(a){var b=.48-a/1.04,c=w.sqrt(.1734+b*b),d=c-b,e=A(z(d),1/3)*(d<0?-1:1),f=-c-b,g=A(z(f),1/3)*(f<0?-1:1),h=e+g+.5;return(1-h)*3*h*h+h*h*h},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a=a-1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){if(a==!!a)return a;return A(2,-10*a)*w.sin((a-.075)*2*B/.3)+1},bounce:function(a){var b=7.5625,c=2.75,d;a<1/c?d=b*a*a:a<2/c?(a-=1.5/c,d=b*a*a+.75):a<2.5/c?(a-=2.25/c,d=b*a*a+.9375):(a-=2.625/c,d=b*a*a+.984375);return d}};cx.easeIn=cx["ease-in"]=cx["<"],cx.easeOut=cx["ease-out"]=cx[">"],cx.easeInOut=cx["ease-in-out"]=cx["<>"],cx["back-in"]=cx.backIn,cx["back-out"]=cx.backOut;var cy=[],cz=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,16)},cA=function(){var b=+(new Date),c=0;for(;c1&&!d.next){for(s in k)k[g](s)&&(r[s]=d.totalOrigin[s]);d.el.attr(r),cE(d.anim,d.el,d.anim.percents[0],null,d.totalOrigin,d.repeat-1)}d.next&&!d.stop&&cE(d.anim,d.el,d.next,null,d.totalOrigin,d.repeat)}}a.svg&&m&&m.paper&&m.paper.safari(),cy.length&&cz(cA)},cB=function(a){return a>255?255:a<0?0:a};cl.animateWith=function(b,c,d,e,f,g){var h=this;if(h.removed){g&&g.call(h);return h}var i=d instanceof cD?d:a.animation(d,e,f,g),j,k;cE(i,h,i.percents[0],null,h.attr());for(var l=0,m=cy.length;l.5)*2-1;i(m-.5,2)+i(n-.5,2)>.25&&(n=f.sqrt(.25-i(m-.5,2))*e+.5)&&n!=.5&&(n=n.toFixed(5)-1e-5*e)}return l}),e=e.split(/\s*\-\s*/);if(j=="linear"){var t=e.shift();t=-d(t);if(isNaN(t))return null;var u=[0,0,f.cos(a.rad(t)),f.sin(a.rad(t))],v=1/(g(h(u[2]),h(u[3]))||1);u[2]*=v,u[3]*=v,u[2]<0&&(u[0]=-u[2],u[2]=0),u[3]<0&&(u[1]=-u[3],u[3]=0)}var w=a._parseDots(e);if(!w)return null;k=k.replace(/[\(\)\s,\xb0#]/g,"_"),b.gradient&&k!=b.gradient.id&&(p.defs.removeChild(b.gradient),delete b.gradient);if(!b.gradient){s=q(j+"Gradient",{id:k}),b.gradient=s,q(s,j=="radial"?{fx:m,fy:n}:{x1:u[0],y1:u[1],x2:u[2],y2:u[3],gradientTransform:b.matrix.invert()}),p.defs.appendChild(s);for(var x=0,y=w.length;x1?G.opacity/100:G.opacity});case"stroke":G=a.getRGB(p),i.setAttribute(o,G.hex),o=="stroke"&&G[b]("opacity")&&q(i,{"stroke-opacity":G.opacity>1?G.opacity/100:G.opacity}),o=="stroke"&&d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1));break;case"gradient":(d.type=="circle"||d.type=="ellipse"||c(p).charAt()!="r")&&r(d,p);break;case"opacity":k.gradient&&!k[b]("stroke-opacity")&&q(i,{"stroke-opacity":p>1?p/100:p});case"fill-opacity":if(k.gradient){H=a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g,l)),H&&(I=H.getElementsByTagName("stop"),q(I[I.length-1],{"stop-opacity":p}));break};default:o=="font-size"&&(p=e(p,10)+"px");var J=o.replace(/(\-.)/g,function(a){return a.substring(1).toUpperCase()});i.style[J]=p,d._.dirty=1,i.setAttribute(o,p)}}y(d,f),i.style.visibility=m},x=1.2,y=function(d,f){if(d.type=="text"&&!!(f[b]("text")||f[b]("font")||f[b]("font-size")||f[b]("x")||f[b]("y"))){var g=d.attrs,h=d.node,i=h.firstChild?e(a._g.doc.defaultView.getComputedStyle(h.firstChild,l).getPropertyValue("font-size"),10):10;if(f[b]("text")){g.text=f.text;while(h.firstChild)h.removeChild(h.firstChild);var j=c(f.text).split("\n"),k=[],m;for(var n=0,o=j.length;n"));var $=X.getBoundingClientRect();t.W=m.w=($.right-$.left)/Y,t.H=m.h=($.bottom-$.top)/Y,t.X=m.x,t.Y=m.y+t.H/2,("x"in i||"y"in i)&&(t.path.v=a.format("m{0},{1}l{2},{1}",f(m.x*u),f(m.y*u),f(m.x*u)+1));var _=["x","y","text","font","font-family","font-weight","font-style","font-size"];for(var ba=0,bb=_.length;ba.25&&(c=e.sqrt(.25-i(b-.5,2))*((c>.5)*2-1)+.5),m=b+n+c);return o}),f=f.split(/\s*\-\s*/);if(l=="linear"){var p=f.shift();p=-d(p);if(isNaN(p))return null}var q=a._parseDots(f);if(!q)return null;b=b.shape||b.node;if(q.length){b.removeChild(g),g.on=!0,g.method="none",g.color=q[0].color,g.color2=q[q.length-1].color;var r=[];for(var s=0,t=q.length;s')}}catch(c){F=function(a){return b.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},a._engine.initWin(a._g.win),a._engine.create=function(){var b=a._getContainer.apply(0,arguments),c=b.container,d=b.height,e,f=b.width,g=b.x,h=b.y;if(!c)throw new Error("VML container not found.");var i=new a._Paper,j=i.canvas=a._g.doc.createElement("div"),k=j.style;g=g||0,h=h||0,f=f||512,d=d||342,i.width=f,i.height=d,f==+f&&(f+="px"),d==+d&&(d+="px"),i.coordsize=u*1e3+n+u*1e3,i.coordorigin="0 0",i.span=a._g.doc.createElement("span"),i.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",j.appendChild(i.span),k.cssText=a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",f,d),c==1?(a._g.doc.body.appendChild(j),k.left=g+"px",k.top=h+"px",k.position="absolute"):c.firstChild?c.insertBefore(j,c.firstChild):c.appendChild(j),i.renderfix=function(){};return i},a.prototype.clear=function(){a.eve("raphael.clear",this),this.canvas.innerHTML=o,this.span=a._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},a.prototype.remove=function(){a.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var b in this)this[b]=typeof this[b]=="function"?a._removedFactory(b):null;return!0};var G=a.st;for(var H in E)E[b](H)&&!G[b](H)&&(G[H]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a].apply(c,b)})}}(H))}(window.Raphael) \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/state-machine.min.js b/node_modules/pathfinding/visual/lib/state-machine.min.js new file mode 100644 index 0000000..e206525 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/state-machine.min.js @@ -0,0 +1 @@ +(function(a){StateMachine={VERSION:"2.1.0",Result:{SUCCEEDED:1,NOTRANSITION:2,CANCELLED:3,ASYNC:4},Error:{INVALID_TRANSITION:100,PENDING_TRANSITION:200,INVALID_CALLBACK:300},WILDCARD:"*",ASYNC:"async",create:function(f,g){var i=(typeof f.initial=="string")?{state:f.initial}:f.initial;var e=g||f.target||{};var k=f.events||[];var h=f.callbacks||{};var c={};var j=function(l){var o=(l.from instanceof Array)?l.from:(l.from?[l.from]:[StateMachine.WILDCARD]);c[l.name]=c[l.name]||{};for(var m=0;mN1x91EQ4=4yQ7#`R^ z$vje}bP0l+XkK DSH>_4 literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-bg_glass_95_fef1ec_1x400.png b/node_modules/pathfinding/visual/lib/themes/images/ui-bg_glass_95_fef1ec_1x400.png new file mode 100644 index 0000000000000000000000000000000000000000..4443fdc1a156babad4336f004eaf5ca5dfa0f9ab GIT binary patch literal 119 zcmeAS@N?(olHy`uVBq!ia0vp^j6gJjgAK^akKnour0hIh978O6-<~(*YA|4MzBvER z|7}eQtdCVXoUc2b{PaWeaIKu7gJx>{vDV26o)#~38k_!`W=^oo1w6ixmPC4R1b Tyd6G3lNdZ*{an^LB{Ts5`idse literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-bg_gloss-wave_16_121212_500x100.png b/node_modules/pathfinding/visual/lib/themes/images/ui-bg_gloss-wave_16_121212_500x100.png new file mode 100644 index 0000000000000000000000000000000000000000..f1a159298743d2448cbf365573d7bd9dda4a0161 GIT binary patch literal 1968 zcmbuAYfzI17KT68U8(M>RaE3wc6KV_5XHDeF5zMop-{C_AvO({m5(GCLMTKMBo}PQ z?hfRFbsO%4VmlRcZHNh=#b_52G<2OtQ02?reZ%T&gE^yU3K69n;qnlNgh*0r*s35GMcJ+Cx5Siy z_)ut^=Qt?*tBy5<$1cW`(9KZd)SXi2ZACzd)+F)?Y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-e< z5cB6(uD*iTy$4(qLwR3DIVCk^M`(O)e*;D`BPGz3OM<3zy4m$maT8}@5?)h2=n7>oNyli}$rkdF zz^IZ+YP(q7#w%!7X%9!i#kzuKmf22hyR-1HLO<5mSCRB!QlOk(qSCz{C~pyXF~|4* gAiMy~*_QpEB}W(v2Ff$mKQWMT;&iIy*xx?>FQwMyMF0Q* literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-hard_15_888888_1x100.png b/node_modules/pathfinding/visual/lib/themes/images/ui-bg_highlight-hard_15_888888_1x100.png new file mode 100644 index 0000000000000000000000000000000000000000..66e53e16c5eb8a113fd0fabc472de38e4765bccc GIT binary patch literal 95 zcmeAS@N?(olHy`uVBq!ia0vp^j6j^i!3HGVb)pi0l$xiDV~E7m>3=i~6%-5_+P)VF=8SHYVO6R2QmdKI;Vst E0J7X4ivR!s literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-bg_inset-soft_15_121212_1x100.png b/node_modules/pathfinding/visual/lib/themes/images/ui-bg_inset-soft_15_121212_1x100.png new file mode 100644 index 0000000000000000000000000000000000000000..9df26a065788f5e40df811c8fcb563a5fbeb5f3e GIT binary patch literal 103 zcmeAS@N?(olHy`uVBq!ia0vp^j6j^i!3HGVb)pi0l%A)HV~E7mWC0v# xhtti?&4z^;2!w&4jm69`r%JGlXHU4NB16C{CJQ00E&f2A44$rjF6*2UngAfo7a9Nn literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-icons_666666_256x240.png b/node_modules/pathfinding/visual/lib/themes/images/ui-icons_666666_256x240.png new file mode 100644 index 0000000000000000000000000000000000000000..f87de1ca1dc2eeefd7c2a4bed06c3f8bbfe2d483 GIT binary patch literal 4369 zcmd^?`8O2)_s3^phOrG}UnfiUEn8(9QW1?MNkxXVDEpFin2{xWrLx5kBC;k~GmC-Ajq!3AfU8Dx90^_ zp3}MKjJzYC+`T(&egFXQ#9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T#aXmjr70%*{{YN6Ky&~A literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-icons_aaaaaa_256x240.png b/node_modules/pathfinding/visual/lib/themes/images/ui-icons_aaaaaa_256x240.png new file mode 100644 index 0000000000000000000000000000000000000000..64af7f11cfef61daf0fdbd80f6f0b7b5448e795a GIT binary patch literal 4369 zcmd^?`8O2)_s3^p#%>t-d@?tR@~?m73Kd(Z3nO0Y&<=YA=b;sjuRVh0kYe-{PG*%20!k}#eNkBB zF`IY6&@1BE{rjV4hX4R~thuSNUGS@Arxe%eMjlANS^0d-bCoc6+6{}d_cotr<+BDe;=!j{I6eOHk2}5K&`;vGhejn`Qlzh+abV9Y!xTe zjNASMPIhvNmjaA^tv9mqeXVn4Y)TR&}K2De8%aV8NTUrZt?W)@)2TTjq(iAE(+=1b~wW0%9P;etL_rz z!R2sbi?0!y!Kf84sPRdl-)T{1U79t}a^<^*XbUT5)2^-h+EaNyFaj?h*(qWpn0N~r zMcLHkn=)8={YOA5*7f+8wuHkuK2hW)$!B?~P3Pjviy2tEKh>)s-L^=EPWFEqWnj>1KsOtsQthJm2b7EFW^7%?hQ$GoC$g*w4yTx>NG}=hMSw z=*CSiB#mGTY%9!m*y1zy1Sb)bb!!IdB;EoRpFqoJS$g**WJc$Z zIzt~~wglN?EWl8-$iN}kaHOLZfxM3xFPcB#wSdFyv0gmH*!N^%9?_ym zRp6rp8MUajtGBj(z&I`nLi^4Fq0;C)bis23HZZ!+kyq!owMwlOsftW;2PG$mLWXjZb18T{4L)*V1C2vU0Ha8qS;; z5|3?qsS!C^16Z>M46u)Pg@4s?C3k{E7;M0~%y zIc_rR;76v*${|OajX{nr<_&Yrmy|JaSQC@mbDNG3d$#ofzm(3>B9{B|qfP*gVeg@dH{Ki{uV_AImC`F3-hmEe!&+$HI$bd{ym?ZywX87i%t?hXSD9z+ zZv=oPJ(52u7lU9y#E;4U(3-OGa<&iT690o-qBf;33nwT%OI-s!eLmOK7Fv-3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T{e)R$7=TWBBCg|w@19X~zXaE2J literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-icons_bbbbbb_256x240.png b/node_modules/pathfinding/visual/lib/themes/images/ui-icons_bbbbbb_256x240.png new file mode 100644 index 0000000000000000000000000000000000000000..9d71edb08dc14962825dcdff02650bd15a35951d GIT binary patch literal 5355 zcmd^@=Q|sY*Ty4}Sh4piwQCoxEwR-evG=T&+F}!1)%@0~QA(-NqAhAh)E+TwrZz>X zn6>%!`8%F-ofn_`-MQ~q_jO(x>T8mdvXBA*0P-hVYQ_Kn!9N5X5QF|voqnkIKk>&< z7opzX+W!A%D{0xE{WGo~V61NfV4{*BBsT1feIv?+@PWHIu+U(koC*voTH5!l_{5Ec z((63dr^qSc`7eB7FgX!x$+n%z+TEMGV#zgM%qk$` z$CP%8LC(AGV;{nO02N_86JbEH$_-;t8wo1nF(_E}WurgT^JuNcFHV@r=~em=zEI1JNrAJ^b{Cnf|Zu$jPaV0+l$Um1vvx)OI_i+0Os9Dfj=rB|m z#p-^w(=Gtf2{Je6WD{U|z^Ox@LlJpjl)D=0n|31aLR>@;?7Gifj~PvBOaydLzk8F| zSh5s2cXyqluW^MlBkStC`mLjjgC>!)qV~;4&T~ASSR+#>MIqJCkLrkO_mrs2McO`E zRm!NaXpJwhr6kYg3h_kZ>8kr{T7g2Y?^6#xGF`|D%J$tcYqJP$nyFnDuX-P6kFNI* z_~yb}MPp~qpWTg)kYcLmy=%JHkQK&}CV9zVt@6h~%l61Fa%Xna;h0A`A-V8K<}>5j zYK~Ma_XI>+c5ja>>X!2U?=u3r zq~02(H0j$y9z!9k?;AfrhdA1zxP@J5PMd5IWWG0IgDW}VozBa+jk7$|bd}RvRyQA? z-Q`zKS`UF5fLx3T=a4_gM|R3AsBZkU0E{cPthE})ZOLBu>eaYm*@NTjbk)bIHgr5R zW+M5@4Wm31lQWZyPKD6F%jqZvNsO^n-t3E$yu)S(O`C%H=GW-RI#OpjRnhUyT+?mG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P%W#6QE~rz`A5ofS9DVEWle&12O`!pEXWB)rrv4mjV{3 zmkj_uRDJy3&)N&n8;7E|i%iTG{TxW!g+?)4StvBrU!A%fakn)g~zJw8t4v=oY6h7CTto-|6-? zH|d_?P^_7)pnHDl4-B+*cQrRiG?NCfom(0kCf)jsKx;QJ;`?EXwwGifW~cXh3l8Q? zN4lPFo>K17eRe_vTuxy@tA>{}@i8F-=BxC>F&_b4y}jzKV2s~7b0?}%#&!BWiD1~au*QK%3;rG90hyerWkY%w`%_wCP67NI;Op}q zyZfT3=T#^+h}3}HV=zAXN8=yhqa1HaCK9Ggm5A`jOKSl6tZgl|ysBvB3taxIj#&?@FD;m#aWM0AeD0yV*WvIL&67z| zH=jur4_?AA;O0v(a2$9>cIh9MwgWUaN^KbAqdq;Ki6u#Bp zzXRdj6P2ZfuBvVNzqcB{J+8kGaQVw&**2-E!T*P%KKjo$Kn z6;o`%9#Hk4nSJ~1l}b|YvOVjUZ1YafRd~!BDWt@=^(vod}=iVB3uns+9GTFZvc4b?|(5&*?d@Hu>EsSU2t7uz2j3G{M*Ue^N zo$OCAMtdFhYqXbsdu`6>^lMp}_f_@l<0ofNXRB7(Mt8n&yohSBefv)iDIwk8rQ zJNc_gaUU?>`fGQtHOOICI&2^v;~kSD9qH})-I2ftBJA1XXK$Ln>bNjArlCblZ1b@J z73zMI*7g~=az>D_Eu?AxLZ!}nsp*9H;0mC6GX3qp+rQ6ELKlyk$|WTvAPxb2OWS3M zg*8(~NR3|N%bxj70DjxXH$QAr9Og)V>o=J}F6N}B%=JZXaUEvxD zfb^OQCJ2znmCB;TP%0hD-uBn~Y&cSQKV#Nyk~JK9W6NoDlimpSBnt$5xNu{WzoooP X_Gc^EhHU=dFY}4IzFMt{L(KmGC|zxE literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/images/ui-icons_c98000_256x240.png b/node_modules/pathfinding/visual/lib/themes/images/ui-icons_c98000_256x240.png new file mode 100644 index 0000000000000000000000000000000000000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es/images/ui-icons_cd0a0a_256x240.png b/node_modules/pathfinding/visual/lib/themes/images/ui-icons_cd0a0a_256x240.png new file mode 100644 index 0000000000000000000000000000000000000000..2ab019b73ec11a485fa09378f3a0e155194f6a5d GIT binary patch literal 4369 zcmd^?`8O2)_s3@pGmLE*`#M>&Z`mr_kcwz5Nh&gy7G+@45H9p05OJ)J0CH2owMSaGIN$+5!N; z<11j56?ANg=9hMl-IBGX-T8hf$N$b*H?$f4Xt&I`oABt1nR=k%#z{{*a!Axm|t}hCz zJg0Ln7;M4Zjx{$mwhMW+kWN;|j>qTx_-zNX!GzqEZRa}QF8_0yk6+=w}$QD^&hM4%OkT=uh$q9;5u~NL-I+NQyaVc|3l+iWI5~|(hA-G z08i8AMr@{uY_cWTxo^y|Qyb33mlZLvc7H2Zm~>mB7&=-1X^@|D z&0*~i?GBE&NM(Pv&Vt^zWu_bD3e|R?wTL{cSFwD^Ij9v%g=aLY@1U2Bxn#Te*{>%D zOOW-O-bfnJ7T8jd<*>8`Z2DsFQi~S$%^npJwXam5>>p zMd}QEjM)@~##n$LXpz1Hkl|2UGXi-JFFePXBWL+-5f%!S>L#KL3>Vl0w#d^21Jn<~_7q zWx^Xg1(>PsPGO&cu{S;(pRQ;=Vw2J<9NdQVWx<+g-`ia=Q@puS)75M+?u>DTa95e9 zt#1T?#a)uWC>Mia!K6>g|InPW{&Kp9$tC_3*;R_Xsz6^Eu|xW1$6j#0?XLs7^l+%O zlxddE)h^|=K(2UqS*0ECuDe0ic|H_^t*VOoTCKx0Qmn_^LyJ|b8l$Jvl3{2=3x8&7 z$1ik&YG>w#@x@y~$r`fhlUDo;yXecc6$`30m`3K8s{k8G&3RVp8n#|l6h(Xw`Axw9 z%6Y^J6k0P@4YAuSd%q7=eg)&u8EMoEmq$CWj1GY|rGQWw3ida!FHk&wCqrQh_0Bcw z!ZBS3CbxgZ+}~wzgGIQ#QId%T_TE~_qdUqxjqS#8#jPxdwO@(@-5_nSP&uT?aGYYD z6km36K9=gj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cv-IT-d%WnC@`FwqbZyHvK$w;~<~5gGDlHIKBNH2FXG` poT7p(d7W6heYSI-)c)Qv>6;IfkTwjq{rlAiSe`|hSDB$>{tt>qUF`q> literal 0 HcmV?d00001 diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.accordion.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.accordion.css new file mode 100644 index 0000000..dacdaee --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.accordion.css @@ -0,0 +1,19 @@ +/* + * jQuery UI Accordion 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Accordion#theming + */ +/* IE/Win - Fix animation bug - #4615 */ +.ui-accordion { width: 100%; } +.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; border: solid 1px #333; background: rgba(0, 0, 0, 0.5); } +.ui-accordion .ui-accordion-li-fix { display: inline; } +.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; } +.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: 0px; } +.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; } +.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } +.ui-accordion .ui-accordion-content { padding: 10px; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; border-radius: 0 0 5px 5px;} +.ui-accordion .ui-accordion-content-active { display: block; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.all.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.all.css new file mode 100644 index 0000000..cd2408b --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.all.css @@ -0,0 +1,11 @@ +/* + * jQuery UI CSS Framework 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming + */ +@import "jquery.ui.base.css"; +@import "jquery.ui.theme.css"; diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.autocomplete.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.autocomplete.css new file mode 100644 index 0000000..269e596 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.autocomplete.css @@ -0,0 +1,53 @@ +/* + * jQuery UI Autocomplete 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Autocomplete#theming + */ +.ui-autocomplete { position: absolute; cursor: default; } + +/* workarounds */ +* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ + +/* + * jQuery UI Menu 1.8.16 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu#theming + */ +.ui-menu { + list-style:none; + padding: 2px; + margin: 0; + display:block; + float: left; +} +.ui-menu .ui-menu { + margin-top: -3px; +} +.ui-menu .ui-menu-item { + margin:0; + padding: 0; + zoom: 1; + float: left; + clear: left; + width: 100%; +} +.ui-menu .ui-menu-item a { + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + zoom:1; +} +.ui-menu .ui-menu-item a.ui-state-hover, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.base.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.base.css new file mode 100644 index 0000000..7f61fc4 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.base.css @@ -0,0 +1,11 @@ +@import url("jquery.ui.core.css"); +@import url("jquery.ui.resizable.css"); +@import url("jquery.ui.selectable.css"); +@import url("jquery.ui.accordion.css"); +@import url("jquery.ui.autocomplete.css"); +@import url("jquery.ui.button.css"); +@import url("jquery.ui.dialog.css"); +@import url("jquery.ui.slider.css"); +@import url("jquery.ui.tabs.css"); +@import url("jquery.ui.datepicker.css"); +@import url("jquery.ui.progressbar.css"); \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.button.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.button.css new file mode 100644 index 0000000..b15ca51 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.button.css @@ -0,0 +1,38 @@ +/* + * jQuery UI Button 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Button#theming + */ +.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ +.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ +button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ +.ui-button-icons-only { width: 3.4em; } +button.ui-button-icons-only { width: 3.7em; } + +/*button text element */ +.ui-button .ui-button-text { display: block; line-height: 1.4; } +.ui-button-text-only .ui-button-text { padding: .4em 1em; } +.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } +.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } +.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } +.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } +/* no icon support for input elements, provide padding by default */ +input.ui-button { padding: .4em 1em; } + +/*button icon element(s) */ +.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } +.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } +.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } +.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } +.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } + +/*button sets*/ +.ui-buttonset { margin-right: 7px; } +.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } + +/* workarounds */ +button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.core.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.core.css new file mode 100644 index 0000000..cd624f6 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.core.css @@ -0,0 +1,41 @@ +/* + * jQuery UI CSS Framework 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { display: none; } +.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } +.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } +.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } +.ui-helper-clearfix { display: inline-block; } +/* required comment for clearfix to work in Opera \*/ +* html .ui-helper-clearfix { height:1%; } +.ui-helper-clearfix { display:block; } +/* end clearfix */ +.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { cursor: default !important; } + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.datepicker.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.datepicker.css new file mode 100644 index 0000000..dcb949e --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.datepicker.css @@ -0,0 +1,68 @@ +/* + * jQuery UI Datepicker 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Datepicker#theming + */ +.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } +.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } +.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } +.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } +.ui-datepicker .ui-datepicker-prev { left:2px; } +.ui-datepicker .ui-datepicker-next { right:2px; } +.ui-datepicker .ui-datepicker-prev-hover { left:1px; } +.ui-datepicker .ui-datepicker-next-hover { right:1px; } +.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } +.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } +.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } +.ui-datepicker select.ui-datepicker-month-year {width: 100%;} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { width: 49%;} +.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } +.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } +.ui-datepicker td { border: 0; padding: 1px; } +.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } +.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } +.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { width:auto; } +.ui-datepicker-multi .ui-datepicker-group { float:left; } +.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } +.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } +.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } +.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } +.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } + +/* RTL support */ +.ui-datepicker-rtl { direction: rtl; } +.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } +.ui-datepicker-rtl .ui-datepicker-group { float:right; } +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } + +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-datepicker-cover { + display: none; /*sorry for IE5*/ + display/**/: block; /*sorry for IE5*/ + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ +} \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.dialog.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.dialog.css new file mode 100644 index 0000000..57798ea --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.dialog.css @@ -0,0 +1,21 @@ +/* + * jQuery UI Dialog 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Dialog#theming + */ +.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } +.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } +.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } +.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } +.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } +.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } +.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } +.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } +.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } +.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } +.ui-draggable .ui-dialog-titlebar { cursor: move; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.progressbar.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.progressbar.css new file mode 100644 index 0000000..8c7ef1c --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.progressbar.css @@ -0,0 +1,11 @@ +/* + * jQuery UI Progressbar 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Progressbar#theming + */ +.ui-progressbar { height:2em; text-align: left; } +.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; } \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.resizable.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.resizable.css new file mode 100644 index 0000000..fabd321 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.resizable.css @@ -0,0 +1,20 @@ +/* + * jQuery UI Resizable 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Resizable#theming + */ +.ui-resizable { position: relative;} +.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block; } +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } +.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } +.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } +.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } +.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } +.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } +.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } +.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } +.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;} \ No newline at end of file diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.selectable.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.selectable.css new file mode 100644 index 0000000..fa01aae --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.selectable.css @@ -0,0 +1,10 @@ +/* + * jQuery UI Selectable 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Selectable#theming + */ +.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.slider.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.slider.css new file mode 100644 index 0000000..a8faa91 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.slider.css @@ -0,0 +1,24 @@ +/* + * jQuery UI Slider 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Slider#theming + */ +.ui-slider { position: relative; text-align: left; background: rgba(255, 255, 255, 0.3) !important; border: none !important;} +.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 15px; height: 15px; cursor: default;} +.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } + +.ui-slider-horizontal { height: 5px; margin-bottom: 15px; } +.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } +.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } +.ui-slider-horizontal .ui-slider-range-min { left: 0; } +.ui-slider-horizontal .ui-slider-range-max { right: 0; } + +.ui-slider-vertical { width: .8em; height: 100px; } +.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } +.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } +.ui-slider-vertical .ui-slider-range-min { bottom: 0; } +.ui-slider-vertical .ui-slider-range-max { top: 0; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.tabs.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.tabs.css new file mode 100644 index 0000000..5173733 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.tabs.css @@ -0,0 +1,18 @@ +/* + * jQuery UI Tabs 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Tabs#theming + */ +.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ +.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } +.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; } +.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; } +.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } +.ui-tabs .ui-tabs-hide { display: none !important; } diff --git a/node_modules/pathfinding/visual/lib/themes/jquery.ui.theme.css b/node_modules/pathfinding/visual/lib/themes/jquery.ui.theme.css new file mode 100644 index 0000000..56a77a6 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/themes/jquery.ui.theme.css @@ -0,0 +1,249 @@ + + +/* + * jQuery UI CSS Framework 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + * + * To view and modify this theme, visit http://jqueryui.com/themeroller/?tr&ffDefault=Helvetica,%20Arial,%20sans-serif&fwDefault=normal&fsDefault=1.1&fsDefaultUnit=em&cornerRadius=5&cornerRadiusUnit=px&bgColorHeader=888888&bgTextureHeader=04_highlight_hard.png&bgImgOpacityHeader=15&borderColorHeader=404040&fcHeader=ffffff&iconColorHeader=cccccc&bgColorContent=121212&bgTextureContent=12_gloss_wave.png&bgImgOpacityContent=16&borderColorContent=404040&fcContent=eeeeee&iconColorContent=bbbbbb&bgColorDefault=adadad&bgTextureDefault=03_highlight_soft.png&bgImgOpacityDefault=35&borderColorDefault=cccccc&fcDefault=333333&iconColorDefault=666666&bgColorHover=dddddd&bgTextureHover=03_highlight_soft.png&bgImgOpacityHover=60&borderColorHover=dddddd&fcHover=000000&iconColorHover=c98000&bgColorActive=121212&bgTextureActive=05_inset_soft.png&bgImgOpacityActive=15&borderColorActive=000000&fcActive=ffffff&iconColorActive=f29a00&bgColorHighlight=555555&bgTextureHighlight=04_highlight_hard.png&bgImgOpacityHighlight=55&borderColorHighlight=404040&fcHighlight=cccccc&iconColorHighlight=aaaaaa&bgColorError=fef1ec&bgTextureError=02_glass.png&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a + */ + + +/* Component containers +----------------------------------*/ +.ui-widget { font-family: Helvetica, Arial, sans-serif; font-size: 1.1em; } +.ui-widget .ui-widget { font-size: 1em; } +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Helvetica, Arial, sans-serif; font-size: 1em; } +.ui-widget-content { border: 1px solid #404040; background: rgba(0, 0, 0, 0.3); color: #eeeeee; } +.ui-widget-content a { color: #eeeeee; } +.ui-widget-header { border: 1px solid #404040; background: #888888; color: #ffffff; font-weight: normal; } +.ui-widget-header a { color: #ffffff; } + +/* Interaction states +----------------------------------*/ +.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #333; background: rgba(0, 0, 0, 0.5); font-weight: normal; color: #ddd; } +.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #ddd; text-decoration: none; } +.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #333; background: rgba(0, 0, 0, 0.2); font-weight: normal; color: #ddd; } +.ui-state-hover a, .ui-state-hover a:hover { color: #fff; text-decoration: none; }A +.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #333; background: rgba(0, 0, 0, 0.5); font-weight: normal; color: #ffffff; } +.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; } +.ui-widget :active { outline: none; } + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #404040; background: #555555 url(images/ui-bg_highlight-hard_55_555555_1x100.png) 50% top repeat-x; color: #cccccc; } +.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #cccccc; } +.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; } +.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; } +.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; } +.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: normal; } +.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } +.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_bbbbbb_256x240.png); } +.ui-widget-content .ui-icon {background-image: url(images/ui-icons_bbbbbb_256x240.png); } +.ui-widget-header .ui-icon {background-image: url(images/ui-icons_cccccc_256x240.png); } +.ui-state-default .ui-icon { background-image: url(images/ui-icons_666666_256x240.png); } +.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_c98000_256x240.png); } +.ui-state-active .ui-icon {background-image: url(images/ui-icons_f29a00_256x240.png); } +.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_aaaaaa_256x240.png); } +.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png); } + +/* positioning */ +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-off { background-position: -96px -144px; } +.ui-icon-radio-on { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; -khtml-border-top-left-radius: 5px; border-top-left-radius: 5px; } +.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -khtml-border-top-right-radius: 5px; border-top-right-radius: 5px; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 5px; -webkit-border-bottom-left-radius: 5px; -khtml-border-bottom-left-radius: 5px; border-bottom-left-radius: 5px; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; -khtml-border-bottom-right-radius: 5px; border-bottom-right-radius: 5px; } + +/* Overlays */ +.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); } +.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; } diff --git a/node_modules/pathfinding/visual/lib/ui/jquery.ui.accordion.min.js b/node_modules/pathfinding/visual/lib/ui/jquery.ui.accordion.min.js new file mode 100644 index 0000000..813f90d --- /dev/null +++ b/node_modules/pathfinding/visual/lib/ui/jquery.ui.accordion.min.js @@ -0,0 +1,30 @@ +/* + * jQuery UI Accordion 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Accordion + * + * Depends: + * jquery.ui.core.js + * jquery.ui.widget.js + */ +(function(c){c.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var a=this,b=a.options;a.running=0;a.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"); +a.headers=a.element.find(b.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){b.disabled||c(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){b.disabled||c(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){b.disabled||c(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){b.disabled||c(this).removeClass("ui-state-focus")});a.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); +if(b.navigation){var d=a.element.find("a").filter(b.navigationFilter).eq(0);if(d.length){var h=d.closest(".ui-accordion-header");a.active=h.length?h:d.closest(".ui-accordion-content").prev()}}a.active=a._findActive(a.active||b.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");a.active.next().addClass("ui-accordion-content-active");a._createIcons();a.resize();a.element.attr("role","tablist");a.headers.attr("role","tab").bind("keydown.accordion", +function(f){return a._keydown(f)}).next().attr("role","tabpanel");a.headers.not(a.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide();a.active.length?a.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):a.headers.eq(0).attr("tabIndex",0);c.browser.safari||a.headers.find("a").attr("tabIndex",-1);b.event&&a.headers.bind(b.event.split(" ").join(".accordion ")+".accordion",function(f){a._clickHandler.call(a,f,this);f.preventDefault()})},_createIcons:function(){var a= +this.options;if(a.icons){c("").addClass("ui-icon "+a.icons.header).prependTo(this.headers);this.active.children(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"); +this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");if(a.autoHeight||a.fillHeight)b.css("height","");return c.Widget.prototype.destroy.call(this)},_setOption:function(a,b){c.Widget.prototype._setOption.apply(this,arguments);a=="active"&&this.activate(b);if(a=="icons"){this._destroyIcons(); +b&&this._createIcons()}if(a=="disabled")this.headers.add(this.headers.next())[b?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(a){if(!(this.options.disabled||a.altKey||a.ctrlKey)){var b=c.ui.keyCode,d=this.headers.length,h=this.headers.index(a.target),f=false;switch(a.keyCode){case b.RIGHT:case b.DOWN:f=this.headers[(h+1)%d];break;case b.LEFT:case b.UP:f=this.headers[(h-1+d)%d];break;case b.SPACE:case b.ENTER:this._clickHandler({target:a.target},a.target); +a.preventDefault()}if(f){c(a.target).attr("tabIndex",-1);c(f).attr("tabIndex",0);f.focus();return false}return true}},resize:function(){var a=this.options,b;if(a.fillSpace){if(c.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}b=this.element.parent().height();c.browser.msie&&this.element.parent().css("overflow",d);this.headers.each(function(){b-=c(this).outerHeight(true)});this.headers.next().each(function(){c(this).height(Math.max(0,b-c(this).innerHeight()+ +c(this).height()))}).css("overflow","auto")}else if(a.autoHeight){b=0;this.headers.next().each(function(){b=Math.max(b,c(this).height("").height())}).height(b)}return this},activate:function(a){this.options.active=a;a=this._findActive(a)[0];this._clickHandler({target:a},a);return this},_findActive:function(a){return a?typeof a==="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===false?c([]):this.headers.filter(":eq(0)")},_clickHandler:function(a,b){var d=this.options; +if(!d.disabled)if(a.target){a=c(a.currentTarget||b);b=a[0]===this.active[0];d.active=d.collapsible&&b?false:this.headers.index(a);if(!(this.running||!d.collapsible&&b)){var h=this.active;j=a.next();g=this.active.next();e={options:d,newHeader:b&&d.collapsible?c([]):a,oldHeader:this.active,newContent:b&&d.collapsible?c([]):j,oldContent:g};var f=this.headers.index(this.active[0])>this.headers.index(a[0]);this.active=b?c([]):a;this._toggle(j,g,e,b,f);h.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header); +if(!b){a.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected);a.next().addClass("ui-accordion-content-active")}}}else if(d.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");var g=this.active.next(), +e={options:d,newHeader:c([]),oldHeader:d.active,newContent:c([]),oldContent:g},j=this.active=c([]);this._toggle(j,g,e)}},_toggle:function(a,b,d,h,f){var g=this,e=g.options;g.toShow=a;g.toHide=b;g.data=d;var j=function(){if(g)return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data);g.running=b.size()===0?a.size():b.size();if(e.animated){d={};d=e.collapsible&&h?{toShow:c([]),toHide:b,complete:j,down:f,autoHeight:e.autoHeight||e.fillSpace}:{toShow:a,toHide:b,complete:j,down:f,autoHeight:e.autoHeight|| +e.fillSpace};if(!e.proxied)e.proxied=e.animated;if(!e.proxiedDuration)e.proxiedDuration=e.duration;e.animated=c.isFunction(e.proxied)?e.proxied(d):e.proxied;e.duration=c.isFunction(e.proxiedDuration)?e.proxiedDuration(d):e.proxiedDuration;h=c.ui.accordion.animations;var i=e.duration,k=e.animated;if(k&&!h[k]&&!c.easing[k])k="slide";h[k]||(h[k]=function(l){this.slide(l,{easing:k,duration:i||700})});h[k](d)}else{if(e.collapsible&&h)a.toggle();else{b.hide();a.show()}j(true)}b.prev().attr({"aria-expanded":"false", +"aria-selected":"false",tabIndex:-1}).blur();a.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;if(!this.running){this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");if(this.toHide.length)this.toHide.parent()[0].className=this.toHide.parent()[0].className;this._trigger("change",null,this.data)}}});c.extend(c.ui.accordion,{version:"1.8.16", +animations:{slide:function(a,b){a=c.extend({easing:"swing",duration:300},a,b);if(a.toHide.size())if(a.toShow.size()){var d=a.toShow.css("overflow"),h=0,f={},g={},e;b=a.toShow;e=b[0].style.width;b.width(parseInt(b.parent().width(),10)-parseInt(b.css("paddingLeft"),10)-parseInt(b.css("paddingRight"),10)-(parseInt(b.css("borderLeftWidth"),10)||0)-(parseInt(b.css("borderRightWidth"),10)||0));c.each(["height","paddingTop","paddingBottom"],function(j,i){g[i]="hide";j=(""+c.css(a.toShow[0],i)).match(/^([\d+-.]+)(.*)$/); +f[i]={value:j[1],unit:j[2]||"px"}});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(g,{step:function(j,i){if(i.prop=="height")h=i.end-i.start===0?0:(i.now-i.start)/(i.end-i.start);a.toShow[0].style[i.prop]=h*f[i.prop].value+f[i.prop].unit},duration:a.duration,easing:a.easing,complete:function(){a.autoHeight||a.toShow.css("height","");a.toShow.css({width:e,overflow:d});a.complete()}})}else a.toHide.animate({height:"hide", +paddingTop:"hide",paddingBottom:"hide"},a);else a.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},a)},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:200})}}})})(jQuery); diff --git a/node_modules/pathfinding/visual/lib/ui/jquery.ui.core.min.js b/node_modules/pathfinding/visual/lib/ui/jquery.ui.core.min.js new file mode 100644 index 0000000..cab9efb --- /dev/null +++ b/node_modules/pathfinding/visual/lib/ui/jquery.ui.core.min.js @@ -0,0 +1,18 @@ +/*! + * jQuery UI 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI + */ +(function(c,j){function k(a,b){var d=a.nodeName.toLowerCase();if("area"===d){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&l(a)}return(/input|select|textarea|button|object/.test(d)?!a.disabled:"a"==d?a.href||b:b)&&l(a)}function l(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.16", +keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({propAttr:c.fn.prop||c.fn.attr,_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d= +this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this, +"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind((c.support.selectstart?"selectstart": +"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,m,n){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(m)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(n)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight, +outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){return k(a,!isNaN(c.attr(a,"tabindex")))},tabbable:function(a){var b=c.attr(a, +"tabindex"),d=isNaN(b);return(d||b>=0)&&k(a,!d)}});c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&& +a.element[0].parentNode)for(var e=0;e0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a
').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")});return true},_mouseStart:function(a){var b=this.options; +this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}); +this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions();d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);d.ui.ddmanager&&d.ui.ddmanager.dragStart(this,a);return true}, +_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b= +false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&this.options.revert.call(this.element,b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration, +10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},_mouseUp:function(a){this.options.iframeFix===true&&d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});d.ui.ddmanager&&d.ui.ddmanager.dragStop(this,a);return d.ui.mouse.prototype._mouseUp.call(this,a)},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle|| +!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone().removeAttr("id"):this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&& +a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent= +this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"), +10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"), +10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[a.containment=="document"?0:d(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,a.containment=="document"?0:d(window).scrollTop()-this.offset.relative.top-this.offset.parent.top, +(a.containment=="document"?0:d(window).scrollLeft())+d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a.containment=="document"?0:d(window).scrollTop())+(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&a.containment.constructor!=Array){a=d(a.containment);var b=a[0];if(b){a.offset();var c=d(b).css("overflow")!= +"hidden";this.containment=[(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0),(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0),(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"), +10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=a}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+ +this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&& +!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,h=a.pageY;if(this.originalPosition){var g;if(this.containment){if(this.relative_container){g=this.relative_container.offset();g=[this.containment[0]+g.left,this.containment[1]+g.top,this.containment[2]+g.left,this.containment[3]+g.top]}else g=this.containment;if(a.pageX-this.offset.click.leftg[2])e=g[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>g[3])h=g[3]+this.offset.click.top}if(b.grid){h=b.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/b.grid[1])*b.grid[1]:this.originalPageY;h=g?!(h-this.offset.click.topg[3])?h:!(h-this.offset.click.topg[2])?e:!(e-this.offset.click.left=0;i--){var j=c.snapElements[i].left,l=j+c.snapElements[i].width,k=c.snapElements[i].top,m=k+c.snapElements[i].height;if(j-e=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted= +false;a.target==this._mouseDownEvent.target&&b.data(a.target,this.widgetName+".preventClickEvent",true);this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery); diff --git a/node_modules/pathfinding/visual/lib/ui/jquery.ui.slider.min.js b/node_modules/pathfinding/visual/lib/ui/jquery.ui.slider.min.js new file mode 100644 index 0000000..d56e271 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/ui/jquery.ui.slider.min.js @@ -0,0 +1,33 @@ +/* + * jQuery UI Slider 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Slider + * + * Depends: + * jquery.ui.core.js + * jquery.ui.mouse.js + * jquery.ui.widget.js + */ +(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options,c=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f=b.values&&b.values.length||1,e=[];this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+ +this.orientation+" ui-widget ui-widget-content ui-corner-all"+(b.disabled?" ui-slider-disabled ui-disabled":""));this.range=d([]);if(b.range){if(b.range===true){if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}this.range=d("
").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(b.range==="min"||b.range==="max"?" ui-slider-range-"+b.range:""))}for(var j=c.length;j"); +this.handles=c.add(d(e.join("")).appendTo(a.element));this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(g){g.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(b.disabled)d(this).blur();else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(g){d(this).data("index.ui-slider-handle", +g)});this.handles.keydown(function(g){var k=true,l=d(this).data("index.ui-slider-handle"),i,h,m;if(!a.options.disabled){switch(g.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:k=false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");i=a._start(g,l);if(i===false)return}break}m=a.options.step;i=a.options.values&&a.options.values.length? +(h=a.values(l)):(h=a.value());switch(g.keyCode){case d.ui.keyCode.HOME:h=a._valueMin();break;case d.ui.keyCode.END:h=a._valueMax();break;case d.ui.keyCode.PAGE_UP:h=a._trimAlignValue(i+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:h=a._trimAlignValue(i-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(i===a._valueMax())return;h=a._trimAlignValue(i+m);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(i===a._valueMin())return;h=a._trimAlignValue(i- +m);break}a._slide(g,l,h);return k}}).keyup(function(g){var k=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(g,k);a._change(g,k);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy(); +return this},_mouseCapture:function(a){var b=this.options,c,f,e,j,g;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:a.pageX,y:a.pageY});f=this._valueMax()-this._valueMin()+1;j=this;this.handles.each(function(k){var l=Math.abs(c-j.values(k));if(f>l){f=l;e=d(this);g=k}});if(b.range===true&&this.values(1)===b.min){g+=1;e=d(this.handles[g])}if(this._start(a,g)===false)return false; +this._mouseSliding=true;j._handleIndex=g;e.addClass("ui-state-active").focus();b=e.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-e.width()/2,top:a.pageY-b.top-e.height()/2-(parseInt(e.css("borderTopWidth"),10)||0)-(parseInt(e.css("borderBottomWidth"),10)||0)+(parseInt(e.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(a,g,c);return this._animateOff=true},_mouseStart:function(){return true},_mouseDrag:function(a){var b= +this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b;if(this.orientation==="horizontal"){b= +this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b); +c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var f;if(this.options.values&&this.options.values.length){f=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>f||b===1&&c1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}else if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;f=arguments[0];for(e=0;e=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=(a-this._valueMin())%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a= +this.options.range,b=this.options,c=this,f=!this._animateOff?b.animate:false,e,j={},g,k,l,i;if(this.options.values&&this.options.values.length)this.handles.each(function(h){e=(c.values(h)-c._valueMin())/(c._valueMax()-c._valueMin())*100;j[c.orientation==="horizontal"?"left":"bottom"]=e+"%";d(this).stop(1,1)[f?"animate":"css"](j,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(h===0)c.range.stop(1,1)[f?"animate":"css"]({left:e+"%"},b.animate);if(h===1)c.range[f?"animate":"css"]({width:e- +g+"%"},{queue:false,duration:b.animate})}else{if(h===0)c.range.stop(1,1)[f?"animate":"css"]({bottom:e+"%"},b.animate);if(h===1)c.range[f?"animate":"css"]({height:e-g+"%"},{queue:false,duration:b.animate})}g=e});else{k=this.value();l=this._valueMin();i=this._valueMax();e=i!==l?(k-l)/(i-l)*100:0;j[c.orientation==="horizontal"?"left":"bottom"]=e+"%";this.handle.stop(1,1)[f?"animate":"css"](j,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[f?"animate":"css"]({width:e+"%"}, +b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[f?"animate":"css"]({width:100-e+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[f?"animate":"css"]({height:e+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[f?"animate":"css"]({height:100-e+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.8.16"})})(jQuery); diff --git a/node_modules/pathfinding/visual/lib/ui/jquery.ui.widget.min.js b/node_modules/pathfinding/visual/lib/ui/jquery.ui.widget.min.js new file mode 100644 index 0000000..4d803c7 --- /dev/null +++ b/node_modules/pathfinding/visual/lib/ui/jquery.ui.widget.min.js @@ -0,0 +1,15 @@ +/*! + * jQuery UI Widget 1.8.16 + * + * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Widget + */ +(function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)try{b(d).triggerHandler("remove")}catch(e){}k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(d){}});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]= +function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)): +d;if(e&&d.charAt(0)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options= +b.extend(true,{},this.options,this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+ +"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}this._setOptions(d);return this},_setOptions:function(a){var c=this;b.each(a,function(d,e){c._setOption(d,e)});return this},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled", +c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery); diff --git a/node_modules/pathfinding/visual/notsupported.html b/node_modules/pathfinding/visual/notsupported.html new file mode 100644 index 0000000..fa23579 --- /dev/null +++ b/node_modules/pathfinding/visual/notsupported.html @@ -0,0 +1,28 @@ + + + + + PathFinding.js + + + +
+ Sorry, your browser is not supported +
+ + diff --git a/node_modules/socket.io-client/LICENSE b/node_modules/socket.io-client/LICENSE new file mode 100644 index 0000000..9338df1 --- /dev/null +++ b/node_modules/socket.io-client/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 Guillermo Rauch + + +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/node_modules/socket.io-client/README.md b/node_modules/socket.io-client/README.md new file mode 100644 index 0000000..b0f199e --- /dev/null +++ b/node_modules/socket.io-client/README.md @@ -0,0 +1,29 @@ + +# socket.io-client + +[![Build Status](https://github.com/socketio/socket.io-client/workflows/CI/badge.svg?branch=main)](https://github.com/socketio/socket.io-client/actions) +[![NPM version](https://badge.fury.io/js/socket.io-client.svg)](https://www.npmjs.com/package/socket.io-client) +![Downloads](http://img.shields.io/npm/dm/socket.io-client.svg?style=flat) +[![](http://slack.socket.io/badge.svg?)](http://slack.socket.io) + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/socket.svg)](https://saucelabs.com/u/socket) + +## Documentation + +Please see the documentation [here](https://socket.io/docs/v4/client-initialization/). + +The source code of the website can be found [here](https://github.com/socketio/socket.io-website). Contributions are welcome! + +## Debug / logging + +In order to see all the client debug output, run the following command on the browser console – including the desired scope – and reload your app page: + +``` +localStorage.debug = '*'; +``` + +And then, filter by the scopes you're interested in. See also: https://socket.io/docs/v4/logging-and-debugging/ + +## License + +[MIT](/LICENSE) diff --git a/node_modules/socket.io-client/build/cjs/browser-entrypoint.js b/node_modules/socket.io-client/build/cjs/browser-entrypoint.js new file mode 100644 index 0000000..c727722 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/browser-entrypoint.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("./index.js"); +exports.default = index_js_1.io; diff --git a/node_modules/socket.io-client/build/cjs/contrib/backo2.js b/node_modules/socket.io-client/build/cjs/contrib/backo2.js new file mode 100644 index 0000000..063fc42 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/contrib/backo2.js @@ -0,0 +1,70 @@ +"use strict"; +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Backoff = void 0; +function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; +} +exports.Backoff = Backoff; +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ +Backoff.prototype.duration = function () { + var ms = this.ms * Math.pow(this.factor, this.attempts++); + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; + } + return Math.min(ms, this.max) | 0; +}; +/** + * Reset the number of attempts. + * + * @api public + */ +Backoff.prototype.reset = function () { + this.attempts = 0; +}; +/** + * Set the minimum duration + * + * @api public + */ +Backoff.prototype.setMin = function (min) { + this.ms = min; +}; +/** + * Set the maximum duration + * + * @api public + */ +Backoff.prototype.setMax = function (max) { + this.max = max; +}; +/** + * Set the jitter + * + * @api public + */ +Backoff.prototype.setJitter = function (jitter) { + this.jitter = jitter; +}; diff --git a/node_modules/socket.io-client/build/cjs/index.js b/node_modules/socket.io-client/build/cjs/index.js new file mode 100644 index 0000000..918d6f3 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/index.js @@ -0,0 +1,69 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports.connect = exports.io = exports.Socket = exports.Manager = exports.protocol = void 0; +const url_js_1 = require("./url.js"); +const manager_js_1 = require("./manager.js"); +Object.defineProperty(exports, "Manager", { enumerable: true, get: function () { return manager_js_1.Manager; } }); +const socket_js_1 = require("./socket.js"); +Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } }); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = debug_1.default("socket.io-client"); // debug() +/** + * Managers cache. + */ +const cache = {}; +function lookup(uri, opts) { + if (typeof uri === "object") { + opts = uri; + uri = undefined; + } + opts = opts || {}; + const parsed = url_js_1.url(uri, opts.path || "/socket.io"); + const source = parsed.source; + const id = parsed.id; + const path = parsed.path; + const sameNamespace = cache[id] && path in cache[id]["nsps"]; + const newConnection = opts.forceNew || + opts["force new connection"] || + false === opts.multiplex || + sameNamespace; + let io; + if (newConnection) { + debug("ignoring socket cache for %s", source); + io = new manager_js_1.Manager(source, opts); + } + else { + if (!cache[id]) { + debug("new io instance for %s", source); + cache[id] = new manager_js_1.Manager(source, opts); + } + io = cache[id]; + } + if (parsed.query && !opts.query) { + opts.query = parsed.queryKey; + } + return io.socket(parsed.path, opts); +} +exports.io = lookup; +exports.connect = lookup; +exports.default = lookup; +// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a +// namespace (e.g. `io.connect(...)`), for backward compatibility +Object.assign(lookup, { + Manager: manager_js_1.Manager, + Socket: socket_js_1.Socket, + io: lookup, + connect: lookup, +}); +/** + * Protocol version. + * + * @public + */ +var socket_io_parser_1 = require("socket.io-parser"); +Object.defineProperty(exports, "protocol", { enumerable: true, get: function () { return socket_io_parser_1.protocol; } }); + +module.exports = lookup; diff --git a/node_modules/socket.io-client/build/cjs/manager.js b/node_modules/socket.io-client/build/cjs/manager.js new file mode 100644 index 0000000..288c6ff --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/manager.js @@ -0,0 +1,395 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Manager = void 0; +const engine_io_client_1 = require("engine.io-client"); +const socket_js_1 = require("./socket.js"); +const parser = __importStar(require("socket.io-parser")); +const on_js_1 = require("./on.js"); +const backo2_js_1 = require("./contrib/backo2.js"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = debug_1.default("socket.io-client:manager"); // debug() +class Manager extends component_emitter_1.Emitter { + constructor(uri, opts) { + var _a; + super(); + this.nsps = {}; + this.subs = []; + if (uri && "object" === typeof uri) { + opts = uri; + uri = undefined; + } + opts = opts || {}; + opts.path = opts.path || "/socket.io"; + this.opts = opts; + engine_io_client_1.installTimerFunctions(this, opts); + this.reconnection(opts.reconnection !== false); + this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); + this.reconnectionDelay(opts.reconnectionDelay || 1000); + this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); + this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5); + this.backoff = new backo2_js_1.Backoff({ + min: this.reconnectionDelay(), + max: this.reconnectionDelayMax(), + jitter: this.randomizationFactor(), + }); + this.timeout(null == opts.timeout ? 20000 : opts.timeout); + this._readyState = "closed"; + this.uri = uri; + const _parser = opts.parser || parser; + this.encoder = new _parser.Encoder(); + this.decoder = new _parser.Decoder(); + this._autoConnect = opts.autoConnect !== false; + if (this._autoConnect) + this.open(); + } + reconnection(v) { + if (!arguments.length) + return this._reconnection; + this._reconnection = !!v; + return this; + } + reconnectionAttempts(v) { + if (v === undefined) + return this._reconnectionAttempts; + this._reconnectionAttempts = v; + return this; + } + reconnectionDelay(v) { + var _a; + if (v === undefined) + return this._reconnectionDelay; + this._reconnectionDelay = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); + return this; + } + randomizationFactor(v) { + var _a; + if (v === undefined) + return this._randomizationFactor; + this._randomizationFactor = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); + return this; + } + reconnectionDelayMax(v) { + var _a; + if (v === undefined) + return this._reconnectionDelayMax; + this._reconnectionDelayMax = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); + return this; + } + timeout(v) { + if (!arguments.length) + return this._timeout; + this._timeout = v; + return this; + } + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + maybeReconnectOnOpen() { + // Only try to reconnect if it's the first time we're connecting + if (!this._reconnecting && + this._reconnection && + this.backoff.attempts === 0) { + // keeps reconnection from firing twice for the same reconnection loop + this.reconnect(); + } + } + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + open(fn) { + debug("readyState %s", this._readyState); + if (~this._readyState.indexOf("open")) + return this; + debug("opening %s", this.uri); + this.engine = new engine_io_client_1.Socket(this.uri, this.opts); + const socket = this.engine; + const self = this; + this._readyState = "opening"; + this.skipReconnect = false; + // emit `open` + const openSubDestroy = on_js_1.on(socket, "open", function () { + self.onopen(); + fn && fn(); + }); + // emit `error` + const errorSub = on_js_1.on(socket, "error", (err) => { + debug("error"); + self.cleanup(); + self._readyState = "closed"; + this.emitReserved("error", err); + if (fn) { + fn(err); + } + else { + // Only do this if there is no fn to handle the error + self.maybeReconnectOnOpen(); + } + }); + if (false !== this._timeout) { + const timeout = this._timeout; + debug("connect attempt will timeout after %d", timeout); + if (timeout === 0) { + openSubDestroy(); // prevents a race condition with the 'open' event + } + // set timer + const timer = this.setTimeoutFn(() => { + debug("connect attempt timed out after %d", timeout); + openSubDestroy(); + socket.close(); + // @ts-ignore + socket.emit("error", new Error("timeout")); + }, timeout); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + this.subs.push(openSubDestroy); + this.subs.push(errorSub); + return this; + } + /** + * Alias for open() + * + * @return self + * @public + */ + connect(fn) { + return this.open(fn); + } + /** + * Called upon transport open. + * + * @private + */ + onopen() { + debug("open"); + // clear old subs + this.cleanup(); + // mark as open + this._readyState = "open"; + this.emitReserved("open"); + // add new subs + const socket = this.engine; + this.subs.push(on_js_1.on(socket, "ping", this.onping.bind(this)), on_js_1.on(socket, "data", this.ondata.bind(this)), on_js_1.on(socket, "error", this.onerror.bind(this)), on_js_1.on(socket, "close", this.onclose.bind(this)), on_js_1.on(this.decoder, "decoded", this.ondecoded.bind(this))); + } + /** + * Called upon a ping. + * + * @private + */ + onping() { + this.emitReserved("ping"); + } + /** + * Called with data. + * + * @private + */ + ondata(data) { + this.decoder.add(data); + } + /** + * Called when parser fully decodes a packet. + * + * @private + */ + ondecoded(packet) { + this.emitReserved("packet", packet); + } + /** + * Called upon socket error. + * + * @private + */ + onerror(err) { + debug("error", err); + this.emitReserved("error", err); + } + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + socket(nsp, opts) { + let socket = this.nsps[nsp]; + if (!socket) { + socket = new socket_js_1.Socket(this, nsp, opts); + this.nsps[nsp] = socket; + } + return socket; + } + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + _destroy(socket) { + const nsps = Object.keys(this.nsps); + for (const nsp of nsps) { + const socket = this.nsps[nsp]; + if (socket.active) { + debug("socket %s is still active, skipping close", nsp); + return; + } + } + this._close(); + } + /** + * Writes a packet. + * + * @param packet + * @private + */ + _packet(packet) { + debug("writing packet %j", packet); + const encodedPackets = this.encoder.encode(packet); + for (let i = 0; i < encodedPackets.length; i++) { + this.engine.write(encodedPackets[i], packet.options); + } + } + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + cleanup() { + debug("cleanup"); + this.subs.forEach((subDestroy) => subDestroy()); + this.subs.length = 0; + this.decoder.destroy(); + } + /** + * Close the current socket. + * + * @private + */ + _close() { + debug("disconnect"); + this.skipReconnect = true; + this._reconnecting = false; + this.onclose("forced close"); + if (this.engine) + this.engine.close(); + } + /** + * Alias for close() + * + * @private + */ + disconnect() { + return this._close(); + } + /** + * Called upon engine close. + * + * @private + */ + onclose(reason, description) { + debug("closed due to %s", reason); + this.cleanup(); + this.backoff.reset(); + this._readyState = "closed"; + this.emitReserved("close", reason, description); + if (this._reconnection && !this.skipReconnect) { + this.reconnect(); + } + } + /** + * Attempt a reconnection. + * + * @private + */ + reconnect() { + if (this._reconnecting || this.skipReconnect) + return this; + const self = this; + if (this.backoff.attempts >= this._reconnectionAttempts) { + debug("reconnect failed"); + this.backoff.reset(); + this.emitReserved("reconnect_failed"); + this._reconnecting = false; + } + else { + const delay = this.backoff.duration(); + debug("will wait %dms before reconnect attempt", delay); + this._reconnecting = true; + const timer = this.setTimeoutFn(() => { + if (self.skipReconnect) + return; + debug("attempting reconnect"); + this.emitReserved("reconnect_attempt", self.backoff.attempts); + // check again for the case socket closed in above events + if (self.skipReconnect) + return; + self.open((err) => { + if (err) { + debug("reconnect attempt error"); + self._reconnecting = false; + self.reconnect(); + this.emitReserved("reconnect_error", err); + } + else { + debug("reconnect success"); + self.onreconnect(); + } + }); + }, delay); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + } + /** + * Called upon successful reconnect. + * + * @private + */ + onreconnect() { + const attempt = this.backoff.attempts; + this._reconnecting = false; + this.backoff.reset(); + this.emitReserved("reconnect", attempt); + } +} +exports.Manager = Manager; diff --git a/node_modules/socket.io-client/build/cjs/on.js b/node_modules/socket.io-client/build/cjs/on.js new file mode 100644 index 0000000..d0dab78 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/on.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.on = void 0; +function on(obj, ev, fn) { + obj.on(ev, fn); + return function subDestroy() { + obj.off(ev, fn); + }; +} +exports.on = on; diff --git a/node_modules/socket.io-client/build/cjs/socket.js b/node_modules/socket.io-client/build/cjs/socket.js new file mode 100644 index 0000000..0a70c79 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/socket.js @@ -0,0 +1,616 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Socket = void 0; +const socket_io_parser_1 = require("socket.io-parser"); +const on_js_1 = require("./on.js"); +const component_emitter_1 = require("@socket.io/component-emitter"); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = debug_1.default("socket.io-client:socket"); // debug() +/** + * Internal events. + * These events can't be emitted by the user. + */ +const RESERVED_EVENTS = Object.freeze({ + connect: 1, + connect_error: 1, + disconnect: 1, + disconnecting: 1, + // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener + newListener: 1, + removeListener: 1, +}); +class Socket extends component_emitter_1.Emitter { + /** + * `Socket` constructor. + * + * @public + */ + constructor(io, nsp, opts) { + super(); + this.connected = false; + this.receiveBuffer = []; + this.sendBuffer = []; + this.ids = 0; + this.acks = {}; + this.flags = {}; + this.io = io; + this.nsp = nsp; + if (opts && opts.auth) { + this.auth = opts.auth; + } + if (this.io._autoConnect) + this.open(); + } + /** + * Whether the socket is currently disconnected + */ + get disconnected() { + return !this.connected; + } + /** + * Subscribe to open, close and packet events + * + * @private + */ + subEvents() { + if (this.subs) + return; + const io = this.io; + this.subs = [ + on_js_1.on(io, "open", this.onopen.bind(this)), + on_js_1.on(io, "packet", this.onpacket.bind(this)), + on_js_1.on(io, "error", this.onerror.bind(this)), + on_js_1.on(io, "close", this.onclose.bind(this)), + ]; + } + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + get active() { + return !!this.subs; + } + /** + * "Opens" the socket. + * + * @public + */ + connect() { + if (this.connected) + return this; + this.subEvents(); + if (!this.io["_reconnecting"]) + this.io.open(); // ensure open + if ("open" === this.io._readyState) + this.onopen(); + return this; + } + /** + * Alias for connect() + */ + open() { + return this.connect(); + } + /** + * Sends a `message` event. + * + * @return self + * @public + */ + send(...args) { + args.unshift("message"); + this.emit.apply(this, args); + return this; + } + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + emit(ev, ...args) { + if (RESERVED_EVENTS.hasOwnProperty(ev)) { + throw new Error('"' + ev + '" is a reserved event name'); + } + args.unshift(ev); + const packet = { + type: socket_io_parser_1.PacketType.EVENT, + data: args, + }; + packet.options = {}; + packet.options.compress = this.flags.compress !== false; + // event ack callback + if ("function" === typeof args[args.length - 1]) { + const id = this.ids++; + debug("emitting packet with ack id %d", id); + const ack = args.pop(); + this._registerAckCallback(id, ack); + packet.id = id; + } + const isTransportWritable = this.io.engine && + this.io.engine.transport && + this.io.engine.transport.writable; + const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected); + if (discardPacket) { + debug("discard packet as the transport is not currently writable"); + } + else if (this.connected) { + this.notifyOutgoingListeners(packet); + this.packet(packet); + } + else { + this.sendBuffer.push(packet); + } + this.flags = {}; + return this; + } + /** + * @private + */ + _registerAckCallback(id, ack) { + const timeout = this.flags.timeout; + if (timeout === undefined) { + this.acks[id] = ack; + return; + } + // @ts-ignore + const timer = this.io.setTimeoutFn(() => { + delete this.acks[id]; + for (let i = 0; i < this.sendBuffer.length; i++) { + if (this.sendBuffer[i].id === id) { + debug("removing packet with ack id %d from the buffer", id); + this.sendBuffer.splice(i, 1); + } + } + debug("event with ack id %d has timed out after %d ms", id, timeout); + ack.call(this, new Error("operation has timed out")); + }, timeout); + this.acks[id] = (...args) => { + // @ts-ignore + this.io.clearTimeoutFn(timer); + ack.apply(this, [null, ...args]); + }; + } + /** + * Sends a packet. + * + * @param packet + * @private + */ + packet(packet) { + packet.nsp = this.nsp; + this.io._packet(packet); + } + /** + * Called upon engine `open`. + * + * @private + */ + onopen() { + debug("transport is open - connecting"); + if (typeof this.auth == "function") { + this.auth((data) => { + this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data }); + }); + } + else { + this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: this.auth }); + } + } + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + onerror(err) { + if (!this.connected) { + this.emitReserved("connect_error", err); + } + } + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + onclose(reason, description) { + debug("close (%s)", reason); + this.connected = false; + delete this.id; + this.emitReserved("disconnect", reason, description); + } + /** + * Called with socket packet. + * + * @param packet + * @private + */ + onpacket(packet) { + const sameNamespace = packet.nsp === this.nsp; + if (!sameNamespace) + return; + switch (packet.type) { + case socket_io_parser_1.PacketType.CONNECT: + if (packet.data && packet.data.sid) { + const id = packet.data.sid; + this.onconnect(id); + } + else { + this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)")); + } + break; + case socket_io_parser_1.PacketType.EVENT: + case socket_io_parser_1.PacketType.BINARY_EVENT: + this.onevent(packet); + break; + case socket_io_parser_1.PacketType.ACK: + case socket_io_parser_1.PacketType.BINARY_ACK: + this.onack(packet); + break; + case socket_io_parser_1.PacketType.DISCONNECT: + this.ondisconnect(); + break; + case socket_io_parser_1.PacketType.CONNECT_ERROR: + this.destroy(); + const err = new Error(packet.data.message); + // @ts-ignore + err.data = packet.data.data; + this.emitReserved("connect_error", err); + break; + } + } + /** + * Called upon a server event. + * + * @param packet + * @private + */ + onevent(packet) { + const args = packet.data || []; + debug("emitting event %j", args); + if (null != packet.id) { + debug("attaching ack callback to event"); + args.push(this.ack(packet.id)); + } + if (this.connected) { + this.emitEvent(args); + } + else { + this.receiveBuffer.push(Object.freeze(args)); + } + } + emitEvent(args) { + if (this._anyListeners && this._anyListeners.length) { + const listeners = this._anyListeners.slice(); + for (const listener of listeners) { + listener.apply(this, args); + } + } + super.emit.apply(this, args); + } + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + ack(id) { + const self = this; + let sent = false; + return function (...args) { + // prevent double callbacks + if (sent) + return; + sent = true; + debug("sending ack %j", args); + self.packet({ + type: socket_io_parser_1.PacketType.ACK, + id: id, + data: args, + }); + }; + } + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + onack(packet) { + const ack = this.acks[packet.id]; + if ("function" === typeof ack) { + debug("calling ack %s with %j", packet.id, packet.data); + ack.apply(this, packet.data); + delete this.acks[packet.id]; + } + else { + debug("bad ack %s", packet.id); + } + } + /** + * Called upon server connect. + * + * @private + */ + onconnect(id) { + debug("socket connected with id %s", id); + this.id = id; + this.connected = true; + this.emitBuffered(); + this.emitReserved("connect"); + } + /** + * Emit buffered events (received and emitted). + * + * @private + */ + emitBuffered() { + this.receiveBuffer.forEach((args) => this.emitEvent(args)); + this.receiveBuffer = []; + this.sendBuffer.forEach((packet) => { + this.notifyOutgoingListeners(packet); + this.packet(packet); + }); + this.sendBuffer = []; + } + /** + * Called upon server disconnect. + * + * @private + */ + ondisconnect() { + debug("server disconnect (%s)", this.nsp); + this.destroy(); + this.onclose("io server disconnect"); + } + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + destroy() { + if (this.subs) { + // clean subscriptions to avoid reconnections + this.subs.forEach((subDestroy) => subDestroy()); + this.subs = undefined; + } + this.io["_destroy"](this); + } + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + disconnect() { + if (this.connected) { + debug("performing disconnect (%s)", this.nsp); + this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT }); + } + // remove socket from pool + this.destroy(); + if (this.connected) { + // fire events + this.onclose("io client disconnect"); + } + return this; + } + /** + * Alias for disconnect() + * + * @return self + * @public + */ + close() { + return this.disconnect(); + } + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + compress(compress) { + this.flags.compress = compress; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + get volatile() { + this.flags.volatile = true; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + timeout(timeout) { + this.flags.timeout = timeout; + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + onAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + prependAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + offAny(listener) { + if (!this._anyListeners) { + return this; + } + if (listener) { + const listeners = this._anyListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAny() { + return this._anyListeners || []; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+     *
+     * socket.onAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + onAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+     *
+     * socket.prependAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + prependAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+     *
+     * const handler = (event, ...args) => {
+     *   console.log(event);
+     * }
+     *
+     * socket.onAnyOutgoing(handler);
+     *
+     * // then later
+     * socket.offAnyOutgoing(handler);
+     *
+     * 
+ * + * @public + */ + offAnyOutgoing(listener) { + if (!this._anyOutgoingListeners) { + return this; + } + if (listener) { + const listeners = this._anyOutgoingListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyOutgoingListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAnyOutgoing() { + return this._anyOutgoingListeners || []; + } + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + notifyOutgoingListeners(packet) { + if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { + const listeners = this._anyOutgoingListeners.slice(); + for (const listener of listeners) { + listener.apply(this, packet.data); + } + } + } +} +exports.Socket = Socket; diff --git a/node_modules/socket.io-client/build/cjs/url.js b/node_modules/socket.io-client/build/cjs/url.js new file mode 100644 index 0000000..b763b70 --- /dev/null +++ b/node_modules/socket.io-client/build/cjs/url.js @@ -0,0 +1,70 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.url = void 0; +const engine_io_client_1 = require("engine.io-client"); +const debug_1 = __importDefault(require("debug")); // debug() +const debug = debug_1.default("socket.io-client:url"); // debug() +/** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ +function url(uri, path = "", loc) { + let obj = uri; + // default to window.location + loc = loc || (typeof location !== "undefined" && location); + if (null == uri) + uri = loc.protocol + "//" + loc.host; + // relative path support + if (typeof uri === "string") { + if ("/" === uri.charAt(0)) { + if ("/" === uri.charAt(1)) { + uri = loc.protocol + uri; + } + else { + uri = loc.host + uri; + } + } + if (!/^(https?|wss?):\/\//.test(uri)) { + debug("protocol-less url %s", uri); + if ("undefined" !== typeof loc) { + uri = loc.protocol + "//" + uri; + } + else { + uri = "https://" + uri; + } + } + // parse + debug("parse %s", uri); + obj = engine_io_client_1.parse(uri); + } + // make sure we treat `localhost:80` and `localhost` equally + if (!obj.port) { + if (/^(http|ws)$/.test(obj.protocol)) { + obj.port = "80"; + } + else if (/^(http|ws)s$/.test(obj.protocol)) { + obj.port = "443"; + } + } + obj.path = obj.path || "/"; + const ipv6 = obj.host.indexOf(":") !== -1; + const host = ipv6 ? "[" + obj.host + "]" : obj.host; + // define unique id + obj.id = obj.protocol + "://" + host + ":" + obj.port + path; + // define href + obj.href = + obj.protocol + + "://" + + host + + (loc && loc.port === obj.port ? "" : ":" + obj.port); + return obj; +} +exports.url = url; diff --git a/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.d.ts b/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.d.ts new file mode 100644 index 0000000..18fe370 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.d.ts @@ -0,0 +1,2 @@ +import { io } from "./index.js"; +export default io; diff --git a/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.js b/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.js new file mode 100644 index 0000000..18fe370 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/browser-entrypoint.js @@ -0,0 +1,2 @@ +import { io } from "./index.js"; +export default io; diff --git a/node_modules/socket.io-client/build/esm-debug/contrib/backo2.d.ts b/node_modules/socket.io-client/build/esm-debug/contrib/backo2.d.ts new file mode 100644 index 0000000..644c735 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/contrib/backo2.d.ts @@ -0,0 +1,12 @@ +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ +export declare function Backoff(opts: any): void; diff --git a/node_modules/socket.io-client/build/esm-debug/contrib/backo2.js b/node_modules/socket.io-client/build/esm-debug/contrib/backo2.js new file mode 100644 index 0000000..8f42c10 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/contrib/backo2.js @@ -0,0 +1,66 @@ +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ +export function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; +} +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ +Backoff.prototype.duration = function () { + var ms = this.ms * Math.pow(this.factor, this.attempts++); + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; + } + return Math.min(ms, this.max) | 0; +}; +/** + * Reset the number of attempts. + * + * @api public + */ +Backoff.prototype.reset = function () { + this.attempts = 0; +}; +/** + * Set the minimum duration + * + * @api public + */ +Backoff.prototype.setMin = function (min) { + this.ms = min; +}; +/** + * Set the maximum duration + * + * @api public + */ +Backoff.prototype.setMax = function (max) { + this.max = max; +}; +/** + * Set the jitter + * + * @api public + */ +Backoff.prototype.setJitter = function (jitter) { + this.jitter = jitter; +}; diff --git a/node_modules/socket.io-client/build/esm-debug/index.d.ts b/node_modules/socket.io-client/build/esm-debug/index.d.ts new file mode 100644 index 0000000..be157f8 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/index.d.ts @@ -0,0 +1,29 @@ +import { Manager, ManagerOptions } from "./manager.js"; +import { Socket, SocketOptions } from "./socket.js"; +/** + * Looks up an existing `Manager` for multiplexing. + * If the user summons: + * + * `io('http://localhost/a');` + * `io('http://localhost/b');` + * + * We reuse the existing instance based on same scheme/port/host, + * and we initialize sockets for each namespace. + * + * @public + */ +declare function lookup(opts?: Partial): Socket; +declare function lookup(uri: string, opts?: Partial): Socket; +declare function lookup(uri: string | Partial, opts?: Partial): Socket; +/** + * Protocol version. + * + * @public + */ +export { protocol } from "socket.io-parser"; +/** + * Expose constructors for standalone build. + * + * @public + */ +export { Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, }; diff --git a/node_modules/socket.io-client/build/esm-debug/index.js b/node_modules/socket.io-client/build/esm-debug/index.js new file mode 100644 index 0000000..6228b08 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/index.js @@ -0,0 +1,61 @@ +import { url } from "./url.js"; +import { Manager } from "./manager.js"; +import { Socket } from "./socket.js"; +import debugModule from "debug"; // debug() +const debug = debugModule("socket.io-client"); // debug() +/** + * Managers cache. + */ +const cache = {}; +function lookup(uri, opts) { + if (typeof uri === "object") { + opts = uri; + uri = undefined; + } + opts = opts || {}; + const parsed = url(uri, opts.path || "/socket.io"); + const source = parsed.source; + const id = parsed.id; + const path = parsed.path; + const sameNamespace = cache[id] && path in cache[id]["nsps"]; + const newConnection = opts.forceNew || + opts["force new connection"] || + false === opts.multiplex || + sameNamespace; + let io; + if (newConnection) { + debug("ignoring socket cache for %s", source); + io = new Manager(source, opts); + } + else { + if (!cache[id]) { + debug("new io instance for %s", source); + cache[id] = new Manager(source, opts); + } + io = cache[id]; + } + if (parsed.query && !opts.query) { + opts.query = parsed.queryKey; + } + return io.socket(parsed.path, opts); +} +// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a +// namespace (e.g. `io.connect(...)`), for backward compatibility +Object.assign(lookup, { + Manager, + Socket, + io: lookup, + connect: lookup, +}); +/** + * Protocol version. + * + * @public + */ +export { protocol } from "socket.io-parser"; +/** + * Expose constructors for standalone build. + * + * @public + */ +export { Manager, Socket, lookup as io, lookup as connect, lookup as default, }; diff --git a/node_modules/socket.io-client/build/esm-debug/manager.d.ts b/node_modules/socket.io-client/build/esm-debug/manager.d.ts new file mode 100644 index 0000000..82cc69d --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/manager.d.ts @@ -0,0 +1,290 @@ +import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client"; +import { Socket, SocketOptions, DisconnectDescription } from "./socket.js"; +import { Packet } from "socket.io-parser"; +import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter"; +export interface ManagerOptions extends EngineOptions { + /** + * Should we force a new Manager for this connection? + * @default false + */ + forceNew: boolean; + /** + * Should we multiplex our connection (reuse existing Manager) ? + * @default true + */ + multiplex: boolean; + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/socket.io' + */ + path: string; + /** + * Should we allow reconnections? + * @default true + */ + reconnection: boolean; + /** + * How many reconnection attempts should we try? + * @default Infinity + */ + reconnectionAttempts: number; + /** + * The time delay in milliseconds between reconnection attempts + * @default 1000 + */ + reconnectionDelay: number; + /** + * The max time delay in milliseconds between reconnection attempts + * @default 5000 + */ + reconnectionDelayMax: number; + /** + * Used in the exponential backoff jitter when reconnecting + * @default 0.5 + */ + randomizationFactor: number; + /** + * The timeout in milliseconds for our connection attempt + * @default 20000 + */ + timeout: number; + /** + * Should we automatically connect? + * @default true + */ + autoConnect: boolean; + /** + * the parser to use. Defaults to an instance of the Parser that ships with socket.io. + */ + parser: any; +} +interface ManagerReservedEvents { + open: () => void; + error: (err: Error) => void; + ping: () => void; + packet: (packet: Packet) => void; + close: (reason: string, description?: DisconnectDescription) => void; + reconnect_failed: () => void; + reconnect_attempt: (attempt: number) => void; + reconnect_error: (err: Error) => void; + reconnect: (attempt: number) => void; +} +export declare class Manager extends Emitter<{}, {}, ManagerReservedEvents> { + /** + * The Engine.IO client instance + * + * @public + */ + engine: Engine; + /** + * @private + */ + _autoConnect: boolean; + /** + * @private + */ + _readyState: "opening" | "open" | "closed"; + /** + * @private + */ + _reconnecting: boolean; + private readonly uri; + opts: Partial; + private nsps; + private subs; + private backoff; + private setTimeoutFn; + private _reconnection; + private _reconnectionAttempts; + private _reconnectionDelay; + private _randomizationFactor; + private _reconnectionDelayMax; + private _timeout; + private encoder; + private decoder; + private skipReconnect; + /** + * `Manager` constructor. + * + * @param uri - engine instance or engine uri/opts + * @param opts - options + * @public + */ + constructor(opts: Partial); + constructor(uri?: string, opts?: Partial); + constructor(uri?: string | Partial, opts?: Partial); + /** + * Sets the `reconnection` config. + * + * @param {Boolean} v - true/false if it should automatically reconnect + * @return {Manager} self or value + * @public + */ + reconnection(v: boolean): this; + reconnection(): boolean; + reconnection(v?: boolean): this | boolean; + /** + * Sets the reconnection attempts config. + * + * @param {Number} v - max reconnection attempts before giving up + * @return {Manager} self or value + * @public + */ + reconnectionAttempts(v: number): this; + reconnectionAttempts(): number; + reconnectionAttempts(v?: number): this | number; + /** + * Sets the delay between reconnections. + * + * @param {Number} v - delay + * @return {Manager} self or value + * @public + */ + reconnectionDelay(v: number): this; + reconnectionDelay(): number; + reconnectionDelay(v?: number): this | number; + /** + * Sets the randomization factor + * + * @param v - the randomization factor + * @return self or value + * @public + */ + randomizationFactor(v: number): this; + randomizationFactor(): number; + randomizationFactor(v?: number): this | number; + /** + * Sets the maximum delay between reconnections. + * + * @param v - delay + * @return self or value + * @public + */ + reconnectionDelayMax(v: number): this; + reconnectionDelayMax(): number; + reconnectionDelayMax(v?: number): this | number; + /** + * Sets the connection timeout. `false` to disable + * + * @param v - connection timeout + * @return self or value + * @public + */ + timeout(v: number | boolean): this; + timeout(): number | boolean; + timeout(v?: number | boolean): this | number | boolean; + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + private maybeReconnectOnOpen; + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + open(fn?: (err?: Error) => void): this; + /** + * Alias for open() + * + * @return self + * @public + */ + connect(fn?: (err?: Error) => void): this; + /** + * Called upon transport open. + * + * @private + */ + private onopen; + /** + * Called upon a ping. + * + * @private + */ + private onping; + /** + * Called with data. + * + * @private + */ + private ondata; + /** + * Called when parser fully decodes a packet. + * + * @private + */ + private ondecoded; + /** + * Called upon socket error. + * + * @private + */ + private onerror; + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + socket(nsp: string, opts?: Partial): Socket; + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + _destroy(socket: Socket): void; + /** + * Writes a packet. + * + * @param packet + * @private + */ + _packet(packet: Partial): void; + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + private cleanup; + /** + * Close the current socket. + * + * @private + */ + _close(): void; + /** + * Alias for close() + * + * @private + */ + private disconnect; + /** + * Called upon engine close. + * + * @private + */ + private onclose; + /** + * Attempt a reconnection. + * + * @private + */ + private reconnect; + /** + * Called upon successful reconnect. + * + * @private + */ + private onreconnect; +} +export {}; diff --git a/node_modules/socket.io-client/build/esm-debug/manager.js b/node_modules/socket.io-client/build/esm-debug/manager.js new file mode 100644 index 0000000..dfab8f5 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/manager.js @@ -0,0 +1,369 @@ +import { Socket as Engine, installTimerFunctions, } from "engine.io-client"; +import { Socket } from "./socket.js"; +import * as parser from "socket.io-parser"; +import { on } from "./on.js"; +import { Backoff } from "./contrib/backo2.js"; +import { Emitter, } from "@socket.io/component-emitter"; +import debugModule from "debug"; // debug() +const debug = debugModule("socket.io-client:manager"); // debug() +export class Manager extends Emitter { + constructor(uri, opts) { + var _a; + super(); + this.nsps = {}; + this.subs = []; + if (uri && "object" === typeof uri) { + opts = uri; + uri = undefined; + } + opts = opts || {}; + opts.path = opts.path || "/socket.io"; + this.opts = opts; + installTimerFunctions(this, opts); + this.reconnection(opts.reconnection !== false); + this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); + this.reconnectionDelay(opts.reconnectionDelay || 1000); + this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); + this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5); + this.backoff = new Backoff({ + min: this.reconnectionDelay(), + max: this.reconnectionDelayMax(), + jitter: this.randomizationFactor(), + }); + this.timeout(null == opts.timeout ? 20000 : opts.timeout); + this._readyState = "closed"; + this.uri = uri; + const _parser = opts.parser || parser; + this.encoder = new _parser.Encoder(); + this.decoder = new _parser.Decoder(); + this._autoConnect = opts.autoConnect !== false; + if (this._autoConnect) + this.open(); + } + reconnection(v) { + if (!arguments.length) + return this._reconnection; + this._reconnection = !!v; + return this; + } + reconnectionAttempts(v) { + if (v === undefined) + return this._reconnectionAttempts; + this._reconnectionAttempts = v; + return this; + } + reconnectionDelay(v) { + var _a; + if (v === undefined) + return this._reconnectionDelay; + this._reconnectionDelay = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); + return this; + } + randomizationFactor(v) { + var _a; + if (v === undefined) + return this._randomizationFactor; + this._randomizationFactor = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); + return this; + } + reconnectionDelayMax(v) { + var _a; + if (v === undefined) + return this._reconnectionDelayMax; + this._reconnectionDelayMax = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); + return this; + } + timeout(v) { + if (!arguments.length) + return this._timeout; + this._timeout = v; + return this; + } + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + maybeReconnectOnOpen() { + // Only try to reconnect if it's the first time we're connecting + if (!this._reconnecting && + this._reconnection && + this.backoff.attempts === 0) { + // keeps reconnection from firing twice for the same reconnection loop + this.reconnect(); + } + } + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + open(fn) { + debug("readyState %s", this._readyState); + if (~this._readyState.indexOf("open")) + return this; + debug("opening %s", this.uri); + this.engine = new Engine(this.uri, this.opts); + const socket = this.engine; + const self = this; + this._readyState = "opening"; + this.skipReconnect = false; + // emit `open` + const openSubDestroy = on(socket, "open", function () { + self.onopen(); + fn && fn(); + }); + // emit `error` + const errorSub = on(socket, "error", (err) => { + debug("error"); + self.cleanup(); + self._readyState = "closed"; + this.emitReserved("error", err); + if (fn) { + fn(err); + } + else { + // Only do this if there is no fn to handle the error + self.maybeReconnectOnOpen(); + } + }); + if (false !== this._timeout) { + const timeout = this._timeout; + debug("connect attempt will timeout after %d", timeout); + if (timeout === 0) { + openSubDestroy(); // prevents a race condition with the 'open' event + } + // set timer + const timer = this.setTimeoutFn(() => { + debug("connect attempt timed out after %d", timeout); + openSubDestroy(); + socket.close(); + // @ts-ignore + socket.emit("error", new Error("timeout")); + }, timeout); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + this.subs.push(openSubDestroy); + this.subs.push(errorSub); + return this; + } + /** + * Alias for open() + * + * @return self + * @public + */ + connect(fn) { + return this.open(fn); + } + /** + * Called upon transport open. + * + * @private + */ + onopen() { + debug("open"); + // clear old subs + this.cleanup(); + // mark as open + this._readyState = "open"; + this.emitReserved("open"); + // add new subs + const socket = this.engine; + this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this))); + } + /** + * Called upon a ping. + * + * @private + */ + onping() { + this.emitReserved("ping"); + } + /** + * Called with data. + * + * @private + */ + ondata(data) { + this.decoder.add(data); + } + /** + * Called when parser fully decodes a packet. + * + * @private + */ + ondecoded(packet) { + this.emitReserved("packet", packet); + } + /** + * Called upon socket error. + * + * @private + */ + onerror(err) { + debug("error", err); + this.emitReserved("error", err); + } + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + socket(nsp, opts) { + let socket = this.nsps[nsp]; + if (!socket) { + socket = new Socket(this, nsp, opts); + this.nsps[nsp] = socket; + } + return socket; + } + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + _destroy(socket) { + const nsps = Object.keys(this.nsps); + for (const nsp of nsps) { + const socket = this.nsps[nsp]; + if (socket.active) { + debug("socket %s is still active, skipping close", nsp); + return; + } + } + this._close(); + } + /** + * Writes a packet. + * + * @param packet + * @private + */ + _packet(packet) { + debug("writing packet %j", packet); + const encodedPackets = this.encoder.encode(packet); + for (let i = 0; i < encodedPackets.length; i++) { + this.engine.write(encodedPackets[i], packet.options); + } + } + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + cleanup() { + debug("cleanup"); + this.subs.forEach((subDestroy) => subDestroy()); + this.subs.length = 0; + this.decoder.destroy(); + } + /** + * Close the current socket. + * + * @private + */ + _close() { + debug("disconnect"); + this.skipReconnect = true; + this._reconnecting = false; + this.onclose("forced close"); + if (this.engine) + this.engine.close(); + } + /** + * Alias for close() + * + * @private + */ + disconnect() { + return this._close(); + } + /** + * Called upon engine close. + * + * @private + */ + onclose(reason, description) { + debug("closed due to %s", reason); + this.cleanup(); + this.backoff.reset(); + this._readyState = "closed"; + this.emitReserved("close", reason, description); + if (this._reconnection && !this.skipReconnect) { + this.reconnect(); + } + } + /** + * Attempt a reconnection. + * + * @private + */ + reconnect() { + if (this._reconnecting || this.skipReconnect) + return this; + const self = this; + if (this.backoff.attempts >= this._reconnectionAttempts) { + debug("reconnect failed"); + this.backoff.reset(); + this.emitReserved("reconnect_failed"); + this._reconnecting = false; + } + else { + const delay = this.backoff.duration(); + debug("will wait %dms before reconnect attempt", delay); + this._reconnecting = true; + const timer = this.setTimeoutFn(() => { + if (self.skipReconnect) + return; + debug("attempting reconnect"); + this.emitReserved("reconnect_attempt", self.backoff.attempts); + // check again for the case socket closed in above events + if (self.skipReconnect) + return; + self.open((err) => { + if (err) { + debug("reconnect attempt error"); + self._reconnecting = false; + self.reconnect(); + this.emitReserved("reconnect_error", err); + } + else { + debug("reconnect success"); + self.onreconnect(); + } + }); + }, delay); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + } + /** + * Called upon successful reconnect. + * + * @private + */ + onreconnect() { + const attempt = this.backoff.attempts; + this._reconnecting = false; + this.backoff.reset(); + this.emitReserved("reconnect", attempt); + } +} diff --git a/node_modules/socket.io-client/build/esm-debug/on.d.ts b/node_modules/socket.io-client/build/esm-debug/on.d.ts new file mode 100644 index 0000000..4179634 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/on.d.ts @@ -0,0 +1,2 @@ +import { Emitter } from "@socket.io/component-emitter"; +export declare function on(obj: Emitter, ev: string, fn: (err?: any) => any): VoidFunction; diff --git a/node_modules/socket.io-client/build/esm-debug/on.js b/node_modules/socket.io-client/build/esm-debug/on.js new file mode 100644 index 0000000..dfe093a --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/on.js @@ -0,0 +1,6 @@ +export function on(obj, ev, fn) { + obj.on(ev, fn); + return function subDestroy() { + obj.off(ev, fn); + }; +} diff --git a/node_modules/socket.io-client/build/esm-debug/package.json b/node_modules/socket.io-client/build/esm-debug/package.json new file mode 100644 index 0000000..a3be54a --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/package.json @@ -0,0 +1,5 @@ +{ + "name": "socket.io-client", + "version": "4.4.0", + "type": "module" +} diff --git a/node_modules/socket.io-client/build/esm-debug/socket.d.ts b/node_modules/socket.io-client/build/esm-debug/socket.d.ts new file mode 100644 index 0000000..87b52bc --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/socket.d.ts @@ -0,0 +1,318 @@ +import { Packet } from "socket.io-parser"; +import { Manager } from "./manager.js"; +import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter"; +export interface SocketOptions { + /** + * the authentication payload sent when connecting to the Namespace + */ + auth: { + [key: string]: any; + } | ((cb: (data: object) => void) => void); +} +export declare type DisconnectDescription = Error | { + description: string; + context?: CloseEvent | XMLHttpRequest; +}; +interface SocketReservedEvents { + connect: () => void; + connect_error: (err: Error) => void; + disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void; +} +export declare class Socket extends Emitter { + readonly io: Manager; + id: string; + connected: boolean; + auth: { + [key: string]: any; + } | ((cb: (data: object) => void) => void); + receiveBuffer: Array>; + sendBuffer: Array; + private readonly nsp; + private ids; + private acks; + private flags; + private subs?; + private _anyListeners; + private _anyOutgoingListeners; + /** + * `Socket` constructor. + * + * @public + */ + constructor(io: Manager, nsp: string, opts?: Partial); + /** + * Whether the socket is currently disconnected + */ + get disconnected(): boolean; + /** + * Subscribe to open, close and packet events + * + * @private + */ + private subEvents; + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + get active(): boolean; + /** + * "Opens" the socket. + * + * @public + */ + connect(): this; + /** + * Alias for connect() + */ + open(): this; + /** + * Sends a `message` event. + * + * @return self + * @public + */ + send(...args: any[]): this; + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + emit>(ev: Ev, ...args: EventParams): this; + /** + * @private + */ + private _registerAckCallback; + /** + * Sends a packet. + * + * @param packet + * @private + */ + private packet; + /** + * Called upon engine `open`. + * + * @private + */ + private onopen; + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + private onerror; + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + private onclose; + /** + * Called with socket packet. + * + * @param packet + * @private + */ + private onpacket; + /** + * Called upon a server event. + * + * @param packet + * @private + */ + private onevent; + private emitEvent; + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + private ack; + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + private onack; + /** + * Called upon server connect. + * + * @private + */ + private onconnect; + /** + * Emit buffered events (received and emitted). + * + * @private + */ + private emitBuffered; + /** + * Called upon server disconnect. + * + * @private + */ + private ondisconnect; + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + private destroy; + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + disconnect(): this; + /** + * Alias for disconnect() + * + * @return self + * @public + */ + close(): this; + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + compress(compress: boolean): this; + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + get volatile(): this; + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + timeout(timeout: number): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + onAny(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + prependAny(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + offAny(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAny(): ((...args: any[]) => void)[]; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+     *
+     * socket.onAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + onAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+     *
+     * socket.prependAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + prependAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+     *
+     * const handler = (event, ...args) => {
+     *   console.log(event);
+     * }
+     *
+     * socket.onAnyOutgoing(handler);
+     *
+     * // then later
+     * socket.offAnyOutgoing(handler);
+     *
+     * 
+ * + * @public + */ + offAnyOutgoing(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAnyOutgoing(): ((...args: any[]) => void)[]; + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + private notifyOutgoingListeners; +} +export declare namespace Socket { + type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error"; +} +export {}; diff --git a/node_modules/socket.io-client/build/esm-debug/socket.js b/node_modules/socket.io-client/build/esm-debug/socket.js new file mode 100644 index 0000000..bfc156c --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/socket.js @@ -0,0 +1,609 @@ +import { PacketType } from "socket.io-parser"; +import { on } from "./on.js"; +import { Emitter, } from "@socket.io/component-emitter"; +import debugModule from "debug"; // debug() +const debug = debugModule("socket.io-client:socket"); // debug() +/** + * Internal events. + * These events can't be emitted by the user. + */ +const RESERVED_EVENTS = Object.freeze({ + connect: 1, + connect_error: 1, + disconnect: 1, + disconnecting: 1, + // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener + newListener: 1, + removeListener: 1, +}); +export class Socket extends Emitter { + /** + * `Socket` constructor. + * + * @public + */ + constructor(io, nsp, opts) { + super(); + this.connected = false; + this.receiveBuffer = []; + this.sendBuffer = []; + this.ids = 0; + this.acks = {}; + this.flags = {}; + this.io = io; + this.nsp = nsp; + if (opts && opts.auth) { + this.auth = opts.auth; + } + if (this.io._autoConnect) + this.open(); + } + /** + * Whether the socket is currently disconnected + */ + get disconnected() { + return !this.connected; + } + /** + * Subscribe to open, close and packet events + * + * @private + */ + subEvents() { + if (this.subs) + return; + const io = this.io; + this.subs = [ + on(io, "open", this.onopen.bind(this)), + on(io, "packet", this.onpacket.bind(this)), + on(io, "error", this.onerror.bind(this)), + on(io, "close", this.onclose.bind(this)), + ]; + } + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + get active() { + return !!this.subs; + } + /** + * "Opens" the socket. + * + * @public + */ + connect() { + if (this.connected) + return this; + this.subEvents(); + if (!this.io["_reconnecting"]) + this.io.open(); // ensure open + if ("open" === this.io._readyState) + this.onopen(); + return this; + } + /** + * Alias for connect() + */ + open() { + return this.connect(); + } + /** + * Sends a `message` event. + * + * @return self + * @public + */ + send(...args) { + args.unshift("message"); + this.emit.apply(this, args); + return this; + } + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + emit(ev, ...args) { + if (RESERVED_EVENTS.hasOwnProperty(ev)) { + throw new Error('"' + ev + '" is a reserved event name'); + } + args.unshift(ev); + const packet = { + type: PacketType.EVENT, + data: args, + }; + packet.options = {}; + packet.options.compress = this.flags.compress !== false; + // event ack callback + if ("function" === typeof args[args.length - 1]) { + const id = this.ids++; + debug("emitting packet with ack id %d", id); + const ack = args.pop(); + this._registerAckCallback(id, ack); + packet.id = id; + } + const isTransportWritable = this.io.engine && + this.io.engine.transport && + this.io.engine.transport.writable; + const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected); + if (discardPacket) { + debug("discard packet as the transport is not currently writable"); + } + else if (this.connected) { + this.notifyOutgoingListeners(packet); + this.packet(packet); + } + else { + this.sendBuffer.push(packet); + } + this.flags = {}; + return this; + } + /** + * @private + */ + _registerAckCallback(id, ack) { + const timeout = this.flags.timeout; + if (timeout === undefined) { + this.acks[id] = ack; + return; + } + // @ts-ignore + const timer = this.io.setTimeoutFn(() => { + delete this.acks[id]; + for (let i = 0; i < this.sendBuffer.length; i++) { + if (this.sendBuffer[i].id === id) { + debug("removing packet with ack id %d from the buffer", id); + this.sendBuffer.splice(i, 1); + } + } + debug("event with ack id %d has timed out after %d ms", id, timeout); + ack.call(this, new Error("operation has timed out")); + }, timeout); + this.acks[id] = (...args) => { + // @ts-ignore + this.io.clearTimeoutFn(timer); + ack.apply(this, [null, ...args]); + }; + } + /** + * Sends a packet. + * + * @param packet + * @private + */ + packet(packet) { + packet.nsp = this.nsp; + this.io._packet(packet); + } + /** + * Called upon engine `open`. + * + * @private + */ + onopen() { + debug("transport is open - connecting"); + if (typeof this.auth == "function") { + this.auth((data) => { + this.packet({ type: PacketType.CONNECT, data }); + }); + } + else { + this.packet({ type: PacketType.CONNECT, data: this.auth }); + } + } + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + onerror(err) { + if (!this.connected) { + this.emitReserved("connect_error", err); + } + } + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + onclose(reason, description) { + debug("close (%s)", reason); + this.connected = false; + delete this.id; + this.emitReserved("disconnect", reason, description); + } + /** + * Called with socket packet. + * + * @param packet + * @private + */ + onpacket(packet) { + const sameNamespace = packet.nsp === this.nsp; + if (!sameNamespace) + return; + switch (packet.type) { + case PacketType.CONNECT: + if (packet.data && packet.data.sid) { + const id = packet.data.sid; + this.onconnect(id); + } + else { + this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)")); + } + break; + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + this.onevent(packet); + break; + case PacketType.ACK: + case PacketType.BINARY_ACK: + this.onack(packet); + break; + case PacketType.DISCONNECT: + this.ondisconnect(); + break; + case PacketType.CONNECT_ERROR: + this.destroy(); + const err = new Error(packet.data.message); + // @ts-ignore + err.data = packet.data.data; + this.emitReserved("connect_error", err); + break; + } + } + /** + * Called upon a server event. + * + * @param packet + * @private + */ + onevent(packet) { + const args = packet.data || []; + debug("emitting event %j", args); + if (null != packet.id) { + debug("attaching ack callback to event"); + args.push(this.ack(packet.id)); + } + if (this.connected) { + this.emitEvent(args); + } + else { + this.receiveBuffer.push(Object.freeze(args)); + } + } + emitEvent(args) { + if (this._anyListeners && this._anyListeners.length) { + const listeners = this._anyListeners.slice(); + for (const listener of listeners) { + listener.apply(this, args); + } + } + super.emit.apply(this, args); + } + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + ack(id) { + const self = this; + let sent = false; + return function (...args) { + // prevent double callbacks + if (sent) + return; + sent = true; + debug("sending ack %j", args); + self.packet({ + type: PacketType.ACK, + id: id, + data: args, + }); + }; + } + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + onack(packet) { + const ack = this.acks[packet.id]; + if ("function" === typeof ack) { + debug("calling ack %s with %j", packet.id, packet.data); + ack.apply(this, packet.data); + delete this.acks[packet.id]; + } + else { + debug("bad ack %s", packet.id); + } + } + /** + * Called upon server connect. + * + * @private + */ + onconnect(id) { + debug("socket connected with id %s", id); + this.id = id; + this.connected = true; + this.emitBuffered(); + this.emitReserved("connect"); + } + /** + * Emit buffered events (received and emitted). + * + * @private + */ + emitBuffered() { + this.receiveBuffer.forEach((args) => this.emitEvent(args)); + this.receiveBuffer = []; + this.sendBuffer.forEach((packet) => { + this.notifyOutgoingListeners(packet); + this.packet(packet); + }); + this.sendBuffer = []; + } + /** + * Called upon server disconnect. + * + * @private + */ + ondisconnect() { + debug("server disconnect (%s)", this.nsp); + this.destroy(); + this.onclose("io server disconnect"); + } + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + destroy() { + if (this.subs) { + // clean subscriptions to avoid reconnections + this.subs.forEach((subDestroy) => subDestroy()); + this.subs = undefined; + } + this.io["_destroy"](this); + } + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + disconnect() { + if (this.connected) { + debug("performing disconnect (%s)", this.nsp); + this.packet({ type: PacketType.DISCONNECT }); + } + // remove socket from pool + this.destroy(); + if (this.connected) { + // fire events + this.onclose("io client disconnect"); + } + return this; + } + /** + * Alias for disconnect() + * + * @return self + * @public + */ + close() { + return this.disconnect(); + } + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + compress(compress) { + this.flags.compress = compress; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + get volatile() { + this.flags.volatile = true; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + timeout(timeout) { + this.flags.timeout = timeout; + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + onAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + prependAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + offAny(listener) { + if (!this._anyListeners) { + return this; + } + if (listener) { + const listeners = this._anyListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAny() { + return this._anyListeners || []; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+     *
+     * socket.onAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + onAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+     *
+     * socket.prependAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + prependAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+     *
+     * const handler = (event, ...args) => {
+     *   console.log(event);
+     * }
+     *
+     * socket.onAnyOutgoing(handler);
+     *
+     * // then later
+     * socket.offAnyOutgoing(handler);
+     *
+     * 
+ * + * @public + */ + offAnyOutgoing(listener) { + if (!this._anyOutgoingListeners) { + return this; + } + if (listener) { + const listeners = this._anyOutgoingListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyOutgoingListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAnyOutgoing() { + return this._anyOutgoingListeners || []; + } + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + notifyOutgoingListeners(packet) { + if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { + const listeners = this._anyOutgoingListeners.slice(); + for (const listener of listeners) { + listener.apply(this, packet.data); + } + } + } +} diff --git a/node_modules/socket.io-client/build/esm-debug/url.d.ts b/node_modules/socket.io-client/build/esm-debug/url.d.ts new file mode 100644 index 0000000..d2d669e --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/url.d.ts @@ -0,0 +1,33 @@ +declare type ParsedUrl = { + source: string; + protocol: string; + authority: string; + userInfo: string; + user: string; + password: string; + host: string; + port: string; + relative: string; + path: string; + directory: string; + file: string; + query: string; + anchor: string; + pathNames: Array; + queryKey: { + [key: string]: string; + }; + id: string; + href: string; +}; +/** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ +export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl; +export {}; diff --git a/node_modules/socket.io-client/build/esm-debug/url.js b/node_modules/socket.io-client/build/esm-debug/url.js new file mode 100644 index 0000000..c61ef30 --- /dev/null +++ b/node_modules/socket.io-client/build/esm-debug/url.js @@ -0,0 +1,63 @@ +import { parse } from "engine.io-client"; +import debugModule from "debug"; // debug() +const debug = debugModule("socket.io-client:url"); // debug() +/** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ +export function url(uri, path = "", loc) { + let obj = uri; + // default to window.location + loc = loc || (typeof location !== "undefined" && location); + if (null == uri) + uri = loc.protocol + "//" + loc.host; + // relative path support + if (typeof uri === "string") { + if ("/" === uri.charAt(0)) { + if ("/" === uri.charAt(1)) { + uri = loc.protocol + uri; + } + else { + uri = loc.host + uri; + } + } + if (!/^(https?|wss?):\/\//.test(uri)) { + debug("protocol-less url %s", uri); + if ("undefined" !== typeof loc) { + uri = loc.protocol + "//" + uri; + } + else { + uri = "https://" + uri; + } + } + // parse + debug("parse %s", uri); + obj = parse(uri); + } + // make sure we treat `localhost:80` and `localhost` equally + if (!obj.port) { + if (/^(http|ws)$/.test(obj.protocol)) { + obj.port = "80"; + } + else if (/^(http|ws)s$/.test(obj.protocol)) { + obj.port = "443"; + } + } + obj.path = obj.path || "/"; + const ipv6 = obj.host.indexOf(":") !== -1; + const host = ipv6 ? "[" + obj.host + "]" : obj.host; + // define unique id + obj.id = obj.protocol + "://" + host + ":" + obj.port + path; + // define href + obj.href = + obj.protocol + + "://" + + host + + (loc && loc.port === obj.port ? "" : ":" + obj.port); + return obj; +} diff --git a/node_modules/socket.io-client/build/esm/browser-entrypoint.d.ts b/node_modules/socket.io-client/build/esm/browser-entrypoint.d.ts new file mode 100644 index 0000000..18fe370 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/browser-entrypoint.d.ts @@ -0,0 +1,2 @@ +import { io } from "./index.js"; +export default io; diff --git a/node_modules/socket.io-client/build/esm/browser-entrypoint.js b/node_modules/socket.io-client/build/esm/browser-entrypoint.js new file mode 100644 index 0000000..18fe370 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/browser-entrypoint.js @@ -0,0 +1,2 @@ +import { io } from "./index.js"; +export default io; diff --git a/node_modules/socket.io-client/build/esm/contrib/backo2.d.ts b/node_modules/socket.io-client/build/esm/contrib/backo2.d.ts new file mode 100644 index 0000000..644c735 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/contrib/backo2.d.ts @@ -0,0 +1,12 @@ +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ +export declare function Backoff(opts: any): void; diff --git a/node_modules/socket.io-client/build/esm/contrib/backo2.js b/node_modules/socket.io-client/build/esm/contrib/backo2.js new file mode 100644 index 0000000..8f42c10 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/contrib/backo2.js @@ -0,0 +1,66 @@ +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ +export function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; +} +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ +Backoff.prototype.duration = function () { + var ms = this.ms * Math.pow(this.factor, this.attempts++); + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; + } + return Math.min(ms, this.max) | 0; +}; +/** + * Reset the number of attempts. + * + * @api public + */ +Backoff.prototype.reset = function () { + this.attempts = 0; +}; +/** + * Set the minimum duration + * + * @api public + */ +Backoff.prototype.setMin = function (min) { + this.ms = min; +}; +/** + * Set the maximum duration + * + * @api public + */ +Backoff.prototype.setMax = function (max) { + this.max = max; +}; +/** + * Set the jitter + * + * @api public + */ +Backoff.prototype.setJitter = function (jitter) { + this.jitter = jitter; +}; diff --git a/node_modules/socket.io-client/build/esm/index.d.ts b/node_modules/socket.io-client/build/esm/index.d.ts new file mode 100644 index 0000000..be157f8 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/index.d.ts @@ -0,0 +1,29 @@ +import { Manager, ManagerOptions } from "./manager.js"; +import { Socket, SocketOptions } from "./socket.js"; +/** + * Looks up an existing `Manager` for multiplexing. + * If the user summons: + * + * `io('http://localhost/a');` + * `io('http://localhost/b');` + * + * We reuse the existing instance based on same scheme/port/host, + * and we initialize sockets for each namespace. + * + * @public + */ +declare function lookup(opts?: Partial): Socket; +declare function lookup(uri: string, opts?: Partial): Socket; +declare function lookup(uri: string | Partial, opts?: Partial): Socket; +/** + * Protocol version. + * + * @public + */ +export { protocol } from "socket.io-parser"; +/** + * Expose constructors for standalone build. + * + * @public + */ +export { Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, }; diff --git a/node_modules/socket.io-client/build/esm/index.js b/node_modules/socket.io-client/build/esm/index.js new file mode 100644 index 0000000..647ec30 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/index.js @@ -0,0 +1,57 @@ +import { url } from "./url.js"; +import { Manager } from "./manager.js"; +import { Socket } from "./socket.js"; +/** + * Managers cache. + */ +const cache = {}; +function lookup(uri, opts) { + if (typeof uri === "object") { + opts = uri; + uri = undefined; + } + opts = opts || {}; + const parsed = url(uri, opts.path || "/socket.io"); + const source = parsed.source; + const id = parsed.id; + const path = parsed.path; + const sameNamespace = cache[id] && path in cache[id]["nsps"]; + const newConnection = opts.forceNew || + opts["force new connection"] || + false === opts.multiplex || + sameNamespace; + let io; + if (newConnection) { + io = new Manager(source, opts); + } + else { + if (!cache[id]) { + cache[id] = new Manager(source, opts); + } + io = cache[id]; + } + if (parsed.query && !opts.query) { + opts.query = parsed.queryKey; + } + return io.socket(parsed.path, opts); +} +// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a +// namespace (e.g. `io.connect(...)`), for backward compatibility +Object.assign(lookup, { + Manager, + Socket, + io: lookup, + connect: lookup, +}); +/** + * Protocol version. + * + * @public + */ +export { protocol } from "socket.io-parser"; +/** + * Expose constructors for standalone build. + * + * @public + */ +export { Manager, Socket, lookup as io, lookup as connect, lookup as default, }; diff --git a/node_modules/socket.io-client/build/esm/manager.d.ts b/node_modules/socket.io-client/build/esm/manager.d.ts new file mode 100644 index 0000000..82cc69d --- /dev/null +++ b/node_modules/socket.io-client/build/esm/manager.d.ts @@ -0,0 +1,290 @@ +import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client"; +import { Socket, SocketOptions, DisconnectDescription } from "./socket.js"; +import { Packet } from "socket.io-parser"; +import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter"; +export interface ManagerOptions extends EngineOptions { + /** + * Should we force a new Manager for this connection? + * @default false + */ + forceNew: boolean; + /** + * Should we multiplex our connection (reuse existing Manager) ? + * @default true + */ + multiplex: boolean; + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/socket.io' + */ + path: string; + /** + * Should we allow reconnections? + * @default true + */ + reconnection: boolean; + /** + * How many reconnection attempts should we try? + * @default Infinity + */ + reconnectionAttempts: number; + /** + * The time delay in milliseconds between reconnection attempts + * @default 1000 + */ + reconnectionDelay: number; + /** + * The max time delay in milliseconds between reconnection attempts + * @default 5000 + */ + reconnectionDelayMax: number; + /** + * Used in the exponential backoff jitter when reconnecting + * @default 0.5 + */ + randomizationFactor: number; + /** + * The timeout in milliseconds for our connection attempt + * @default 20000 + */ + timeout: number; + /** + * Should we automatically connect? + * @default true + */ + autoConnect: boolean; + /** + * the parser to use. Defaults to an instance of the Parser that ships with socket.io. + */ + parser: any; +} +interface ManagerReservedEvents { + open: () => void; + error: (err: Error) => void; + ping: () => void; + packet: (packet: Packet) => void; + close: (reason: string, description?: DisconnectDescription) => void; + reconnect_failed: () => void; + reconnect_attempt: (attempt: number) => void; + reconnect_error: (err: Error) => void; + reconnect: (attempt: number) => void; +} +export declare class Manager extends Emitter<{}, {}, ManagerReservedEvents> { + /** + * The Engine.IO client instance + * + * @public + */ + engine: Engine; + /** + * @private + */ + _autoConnect: boolean; + /** + * @private + */ + _readyState: "opening" | "open" | "closed"; + /** + * @private + */ + _reconnecting: boolean; + private readonly uri; + opts: Partial; + private nsps; + private subs; + private backoff; + private setTimeoutFn; + private _reconnection; + private _reconnectionAttempts; + private _reconnectionDelay; + private _randomizationFactor; + private _reconnectionDelayMax; + private _timeout; + private encoder; + private decoder; + private skipReconnect; + /** + * `Manager` constructor. + * + * @param uri - engine instance or engine uri/opts + * @param opts - options + * @public + */ + constructor(opts: Partial); + constructor(uri?: string, opts?: Partial); + constructor(uri?: string | Partial, opts?: Partial); + /** + * Sets the `reconnection` config. + * + * @param {Boolean} v - true/false if it should automatically reconnect + * @return {Manager} self or value + * @public + */ + reconnection(v: boolean): this; + reconnection(): boolean; + reconnection(v?: boolean): this | boolean; + /** + * Sets the reconnection attempts config. + * + * @param {Number} v - max reconnection attempts before giving up + * @return {Manager} self or value + * @public + */ + reconnectionAttempts(v: number): this; + reconnectionAttempts(): number; + reconnectionAttempts(v?: number): this | number; + /** + * Sets the delay between reconnections. + * + * @param {Number} v - delay + * @return {Manager} self or value + * @public + */ + reconnectionDelay(v: number): this; + reconnectionDelay(): number; + reconnectionDelay(v?: number): this | number; + /** + * Sets the randomization factor + * + * @param v - the randomization factor + * @return self or value + * @public + */ + randomizationFactor(v: number): this; + randomizationFactor(): number; + randomizationFactor(v?: number): this | number; + /** + * Sets the maximum delay between reconnections. + * + * @param v - delay + * @return self or value + * @public + */ + reconnectionDelayMax(v: number): this; + reconnectionDelayMax(): number; + reconnectionDelayMax(v?: number): this | number; + /** + * Sets the connection timeout. `false` to disable + * + * @param v - connection timeout + * @return self or value + * @public + */ + timeout(v: number | boolean): this; + timeout(): number | boolean; + timeout(v?: number | boolean): this | number | boolean; + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + private maybeReconnectOnOpen; + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + open(fn?: (err?: Error) => void): this; + /** + * Alias for open() + * + * @return self + * @public + */ + connect(fn?: (err?: Error) => void): this; + /** + * Called upon transport open. + * + * @private + */ + private onopen; + /** + * Called upon a ping. + * + * @private + */ + private onping; + /** + * Called with data. + * + * @private + */ + private ondata; + /** + * Called when parser fully decodes a packet. + * + * @private + */ + private ondecoded; + /** + * Called upon socket error. + * + * @private + */ + private onerror; + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + socket(nsp: string, opts?: Partial): Socket; + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + _destroy(socket: Socket): void; + /** + * Writes a packet. + * + * @param packet + * @private + */ + _packet(packet: Partial): void; + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + private cleanup; + /** + * Close the current socket. + * + * @private + */ + _close(): void; + /** + * Alias for close() + * + * @private + */ + private disconnect; + /** + * Called upon engine close. + * + * @private + */ + private onclose; + /** + * Attempt a reconnection. + * + * @private + */ + private reconnect; + /** + * Called upon successful reconnect. + * + * @private + */ + private onreconnect; +} +export {}; diff --git a/node_modules/socket.io-client/build/esm/manager.js b/node_modules/socket.io-client/build/esm/manager.js new file mode 100644 index 0000000..d346f4c --- /dev/null +++ b/node_modules/socket.io-client/build/esm/manager.js @@ -0,0 +1,350 @@ +import { Socket as Engine, installTimerFunctions, } from "engine.io-client"; +import { Socket } from "./socket.js"; +import * as parser from "socket.io-parser"; +import { on } from "./on.js"; +import { Backoff } from "./contrib/backo2.js"; +import { Emitter, } from "@socket.io/component-emitter"; +export class Manager extends Emitter { + constructor(uri, opts) { + var _a; + super(); + this.nsps = {}; + this.subs = []; + if (uri && "object" === typeof uri) { + opts = uri; + uri = undefined; + } + opts = opts || {}; + opts.path = opts.path || "/socket.io"; + this.opts = opts; + installTimerFunctions(this, opts); + this.reconnection(opts.reconnection !== false); + this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); + this.reconnectionDelay(opts.reconnectionDelay || 1000); + this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); + this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5); + this.backoff = new Backoff({ + min: this.reconnectionDelay(), + max: this.reconnectionDelayMax(), + jitter: this.randomizationFactor(), + }); + this.timeout(null == opts.timeout ? 20000 : opts.timeout); + this._readyState = "closed"; + this.uri = uri; + const _parser = opts.parser || parser; + this.encoder = new _parser.Encoder(); + this.decoder = new _parser.Decoder(); + this._autoConnect = opts.autoConnect !== false; + if (this._autoConnect) + this.open(); + } + reconnection(v) { + if (!arguments.length) + return this._reconnection; + this._reconnection = !!v; + return this; + } + reconnectionAttempts(v) { + if (v === undefined) + return this._reconnectionAttempts; + this._reconnectionAttempts = v; + return this; + } + reconnectionDelay(v) { + var _a; + if (v === undefined) + return this._reconnectionDelay; + this._reconnectionDelay = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); + return this; + } + randomizationFactor(v) { + var _a; + if (v === undefined) + return this._randomizationFactor; + this._randomizationFactor = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); + return this; + } + reconnectionDelayMax(v) { + var _a; + if (v === undefined) + return this._reconnectionDelayMax; + this._reconnectionDelayMax = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); + return this; + } + timeout(v) { + if (!arguments.length) + return this._timeout; + this._timeout = v; + return this; + } + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + maybeReconnectOnOpen() { + // Only try to reconnect if it's the first time we're connecting + if (!this._reconnecting && + this._reconnection && + this.backoff.attempts === 0) { + // keeps reconnection from firing twice for the same reconnection loop + this.reconnect(); + } + } + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + open(fn) { + if (~this._readyState.indexOf("open")) + return this; + this.engine = new Engine(this.uri, this.opts); + const socket = this.engine; + const self = this; + this._readyState = "opening"; + this.skipReconnect = false; + // emit `open` + const openSubDestroy = on(socket, "open", function () { + self.onopen(); + fn && fn(); + }); + // emit `error` + const errorSub = on(socket, "error", (err) => { + self.cleanup(); + self._readyState = "closed"; + this.emitReserved("error", err); + if (fn) { + fn(err); + } + else { + // Only do this if there is no fn to handle the error + self.maybeReconnectOnOpen(); + } + }); + if (false !== this._timeout) { + const timeout = this._timeout; + if (timeout === 0) { + openSubDestroy(); // prevents a race condition with the 'open' event + } + // set timer + const timer = this.setTimeoutFn(() => { + openSubDestroy(); + socket.close(); + // @ts-ignore + socket.emit("error", new Error("timeout")); + }, timeout); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + this.subs.push(openSubDestroy); + this.subs.push(errorSub); + return this; + } + /** + * Alias for open() + * + * @return self + * @public + */ + connect(fn) { + return this.open(fn); + } + /** + * Called upon transport open. + * + * @private + */ + onopen() { + // clear old subs + this.cleanup(); + // mark as open + this._readyState = "open"; + this.emitReserved("open"); + // add new subs + const socket = this.engine; + this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this))); + } + /** + * Called upon a ping. + * + * @private + */ + onping() { + this.emitReserved("ping"); + } + /** + * Called with data. + * + * @private + */ + ondata(data) { + this.decoder.add(data); + } + /** + * Called when parser fully decodes a packet. + * + * @private + */ + ondecoded(packet) { + this.emitReserved("packet", packet); + } + /** + * Called upon socket error. + * + * @private + */ + onerror(err) { + this.emitReserved("error", err); + } + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + socket(nsp, opts) { + let socket = this.nsps[nsp]; + if (!socket) { + socket = new Socket(this, nsp, opts); + this.nsps[nsp] = socket; + } + return socket; + } + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + _destroy(socket) { + const nsps = Object.keys(this.nsps); + for (const nsp of nsps) { + const socket = this.nsps[nsp]; + if (socket.active) { + return; + } + } + this._close(); + } + /** + * Writes a packet. + * + * @param packet + * @private + */ + _packet(packet) { + const encodedPackets = this.encoder.encode(packet); + for (let i = 0; i < encodedPackets.length; i++) { + this.engine.write(encodedPackets[i], packet.options); + } + } + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + cleanup() { + this.subs.forEach((subDestroy) => subDestroy()); + this.subs.length = 0; + this.decoder.destroy(); + } + /** + * Close the current socket. + * + * @private + */ + _close() { + this.skipReconnect = true; + this._reconnecting = false; + this.onclose("forced close"); + if (this.engine) + this.engine.close(); + } + /** + * Alias for close() + * + * @private + */ + disconnect() { + return this._close(); + } + /** + * Called upon engine close. + * + * @private + */ + onclose(reason, description) { + this.cleanup(); + this.backoff.reset(); + this._readyState = "closed"; + this.emitReserved("close", reason, description); + if (this._reconnection && !this.skipReconnect) { + this.reconnect(); + } + } + /** + * Attempt a reconnection. + * + * @private + */ + reconnect() { + if (this._reconnecting || this.skipReconnect) + return this; + const self = this; + if (this.backoff.attempts >= this._reconnectionAttempts) { + this.backoff.reset(); + this.emitReserved("reconnect_failed"); + this._reconnecting = false; + } + else { + const delay = this.backoff.duration(); + this._reconnecting = true; + const timer = this.setTimeoutFn(() => { + if (self.skipReconnect) + return; + this.emitReserved("reconnect_attempt", self.backoff.attempts); + // check again for the case socket closed in above events + if (self.skipReconnect) + return; + self.open((err) => { + if (err) { + self._reconnecting = false; + self.reconnect(); + this.emitReserved("reconnect_error", err); + } + else { + self.onreconnect(); + } + }); + }, delay); + if (this.opts.autoUnref) { + timer.unref(); + } + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + } + /** + * Called upon successful reconnect. + * + * @private + */ + onreconnect() { + const attempt = this.backoff.attempts; + this._reconnecting = false; + this.backoff.reset(); + this.emitReserved("reconnect", attempt); + } +} diff --git a/node_modules/socket.io-client/build/esm/on.d.ts b/node_modules/socket.io-client/build/esm/on.d.ts new file mode 100644 index 0000000..4179634 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/on.d.ts @@ -0,0 +1,2 @@ +import { Emitter } from "@socket.io/component-emitter"; +export declare function on(obj: Emitter, ev: string, fn: (err?: any) => any): VoidFunction; diff --git a/node_modules/socket.io-client/build/esm/on.js b/node_modules/socket.io-client/build/esm/on.js new file mode 100644 index 0000000..dfe093a --- /dev/null +++ b/node_modules/socket.io-client/build/esm/on.js @@ -0,0 +1,6 @@ +export function on(obj, ev, fn) { + obj.on(ev, fn); + return function subDestroy() { + obj.off(ev, fn); + }; +} diff --git a/node_modules/socket.io-client/build/esm/package.json b/node_modules/socket.io-client/build/esm/package.json new file mode 100644 index 0000000..a3be54a --- /dev/null +++ b/node_modules/socket.io-client/build/esm/package.json @@ -0,0 +1,5 @@ +{ + "name": "socket.io-client", + "version": "4.4.0", + "type": "module" +} diff --git a/node_modules/socket.io-client/build/esm/socket.d.ts b/node_modules/socket.io-client/build/esm/socket.d.ts new file mode 100644 index 0000000..87b52bc --- /dev/null +++ b/node_modules/socket.io-client/build/esm/socket.d.ts @@ -0,0 +1,318 @@ +import { Packet } from "socket.io-parser"; +import { Manager } from "./manager.js"; +import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter"; +export interface SocketOptions { + /** + * the authentication payload sent when connecting to the Namespace + */ + auth: { + [key: string]: any; + } | ((cb: (data: object) => void) => void); +} +export declare type DisconnectDescription = Error | { + description: string; + context?: CloseEvent | XMLHttpRequest; +}; +interface SocketReservedEvents { + connect: () => void; + connect_error: (err: Error) => void; + disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void; +} +export declare class Socket extends Emitter { + readonly io: Manager; + id: string; + connected: boolean; + auth: { + [key: string]: any; + } | ((cb: (data: object) => void) => void); + receiveBuffer: Array>; + sendBuffer: Array; + private readonly nsp; + private ids; + private acks; + private flags; + private subs?; + private _anyListeners; + private _anyOutgoingListeners; + /** + * `Socket` constructor. + * + * @public + */ + constructor(io: Manager, nsp: string, opts?: Partial); + /** + * Whether the socket is currently disconnected + */ + get disconnected(): boolean; + /** + * Subscribe to open, close and packet events + * + * @private + */ + private subEvents; + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + get active(): boolean; + /** + * "Opens" the socket. + * + * @public + */ + connect(): this; + /** + * Alias for connect() + */ + open(): this; + /** + * Sends a `message` event. + * + * @return self + * @public + */ + send(...args: any[]): this; + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + emit>(ev: Ev, ...args: EventParams): this; + /** + * @private + */ + private _registerAckCallback; + /** + * Sends a packet. + * + * @param packet + * @private + */ + private packet; + /** + * Called upon engine `open`. + * + * @private + */ + private onopen; + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + private onerror; + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + private onclose; + /** + * Called with socket packet. + * + * @param packet + * @private + */ + private onpacket; + /** + * Called upon a server event. + * + * @param packet + * @private + */ + private onevent; + private emitEvent; + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + private ack; + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + private onack; + /** + * Called upon server connect. + * + * @private + */ + private onconnect; + /** + * Emit buffered events (received and emitted). + * + * @private + */ + private emitBuffered; + /** + * Called upon server disconnect. + * + * @private + */ + private ondisconnect; + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + private destroy; + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + disconnect(): this; + /** + * Alias for disconnect() + * + * @return self + * @public + */ + close(): this; + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + compress(compress: boolean): this; + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + get volatile(): this; + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + timeout(timeout: number): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + onAny(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + prependAny(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + offAny(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAny(): ((...args: any[]) => void)[]; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+     *
+     * socket.onAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + onAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+     *
+     * socket.prependAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + prependAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+     *
+     * const handler = (event, ...args) => {
+     *   console.log(event);
+     * }
+     *
+     * socket.onAnyOutgoing(handler);
+     *
+     * // then later
+     * socket.offAnyOutgoing(handler);
+     *
+     * 
+ * + * @public + */ + offAnyOutgoing(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAnyOutgoing(): ((...args: any[]) => void)[]; + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + private notifyOutgoingListeners; +} +export declare namespace Socket { + type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error"; +} +export {}; diff --git a/node_modules/socket.io-client/build/esm/socket.js b/node_modules/socket.io-client/build/esm/socket.js new file mode 100644 index 0000000..93a6373 --- /dev/null +++ b/node_modules/socket.io-client/build/esm/socket.js @@ -0,0 +1,593 @@ +import { PacketType } from "socket.io-parser"; +import { on } from "./on.js"; +import { Emitter, } from "@socket.io/component-emitter"; +/** + * Internal events. + * These events can't be emitted by the user. + */ +const RESERVED_EVENTS = Object.freeze({ + connect: 1, + connect_error: 1, + disconnect: 1, + disconnecting: 1, + // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener + newListener: 1, + removeListener: 1, +}); +export class Socket extends Emitter { + /** + * `Socket` constructor. + * + * @public + */ + constructor(io, nsp, opts) { + super(); + this.connected = false; + this.receiveBuffer = []; + this.sendBuffer = []; + this.ids = 0; + this.acks = {}; + this.flags = {}; + this.io = io; + this.nsp = nsp; + if (opts && opts.auth) { + this.auth = opts.auth; + } + if (this.io._autoConnect) + this.open(); + } + /** + * Whether the socket is currently disconnected + */ + get disconnected() { + return !this.connected; + } + /** + * Subscribe to open, close and packet events + * + * @private + */ + subEvents() { + if (this.subs) + return; + const io = this.io; + this.subs = [ + on(io, "open", this.onopen.bind(this)), + on(io, "packet", this.onpacket.bind(this)), + on(io, "error", this.onerror.bind(this)), + on(io, "close", this.onclose.bind(this)), + ]; + } + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + get active() { + return !!this.subs; + } + /** + * "Opens" the socket. + * + * @public + */ + connect() { + if (this.connected) + return this; + this.subEvents(); + if (!this.io["_reconnecting"]) + this.io.open(); // ensure open + if ("open" === this.io._readyState) + this.onopen(); + return this; + } + /** + * Alias for connect() + */ + open() { + return this.connect(); + } + /** + * Sends a `message` event. + * + * @return self + * @public + */ + send(...args) { + args.unshift("message"); + this.emit.apply(this, args); + return this; + } + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + emit(ev, ...args) { + if (RESERVED_EVENTS.hasOwnProperty(ev)) { + throw new Error('"' + ev + '" is a reserved event name'); + } + args.unshift(ev); + const packet = { + type: PacketType.EVENT, + data: args, + }; + packet.options = {}; + packet.options.compress = this.flags.compress !== false; + // event ack callback + if ("function" === typeof args[args.length - 1]) { + const id = this.ids++; + const ack = args.pop(); + this._registerAckCallback(id, ack); + packet.id = id; + } + const isTransportWritable = this.io.engine && + this.io.engine.transport && + this.io.engine.transport.writable; + const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected); + if (discardPacket) { + } + else if (this.connected) { + this.notifyOutgoingListeners(packet); + this.packet(packet); + } + else { + this.sendBuffer.push(packet); + } + this.flags = {}; + return this; + } + /** + * @private + */ + _registerAckCallback(id, ack) { + const timeout = this.flags.timeout; + if (timeout === undefined) { + this.acks[id] = ack; + return; + } + // @ts-ignore + const timer = this.io.setTimeoutFn(() => { + delete this.acks[id]; + for (let i = 0; i < this.sendBuffer.length; i++) { + if (this.sendBuffer[i].id === id) { + this.sendBuffer.splice(i, 1); + } + } + ack.call(this, new Error("operation has timed out")); + }, timeout); + this.acks[id] = (...args) => { + // @ts-ignore + this.io.clearTimeoutFn(timer); + ack.apply(this, [null, ...args]); + }; + } + /** + * Sends a packet. + * + * @param packet + * @private + */ + packet(packet) { + packet.nsp = this.nsp; + this.io._packet(packet); + } + /** + * Called upon engine `open`. + * + * @private + */ + onopen() { + if (typeof this.auth == "function") { + this.auth((data) => { + this.packet({ type: PacketType.CONNECT, data }); + }); + } + else { + this.packet({ type: PacketType.CONNECT, data: this.auth }); + } + } + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + onerror(err) { + if (!this.connected) { + this.emitReserved("connect_error", err); + } + } + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + onclose(reason, description) { + this.connected = false; + delete this.id; + this.emitReserved("disconnect", reason, description); + } + /** + * Called with socket packet. + * + * @param packet + * @private + */ + onpacket(packet) { + const sameNamespace = packet.nsp === this.nsp; + if (!sameNamespace) + return; + switch (packet.type) { + case PacketType.CONNECT: + if (packet.data && packet.data.sid) { + const id = packet.data.sid; + this.onconnect(id); + } + else { + this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)")); + } + break; + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + this.onevent(packet); + break; + case PacketType.ACK: + case PacketType.BINARY_ACK: + this.onack(packet); + break; + case PacketType.DISCONNECT: + this.ondisconnect(); + break; + case PacketType.CONNECT_ERROR: + this.destroy(); + const err = new Error(packet.data.message); + // @ts-ignore + err.data = packet.data.data; + this.emitReserved("connect_error", err); + break; + } + } + /** + * Called upon a server event. + * + * @param packet + * @private + */ + onevent(packet) { + const args = packet.data || []; + if (null != packet.id) { + args.push(this.ack(packet.id)); + } + if (this.connected) { + this.emitEvent(args); + } + else { + this.receiveBuffer.push(Object.freeze(args)); + } + } + emitEvent(args) { + if (this._anyListeners && this._anyListeners.length) { + const listeners = this._anyListeners.slice(); + for (const listener of listeners) { + listener.apply(this, args); + } + } + super.emit.apply(this, args); + } + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + ack(id) { + const self = this; + let sent = false; + return function (...args) { + // prevent double callbacks + if (sent) + return; + sent = true; + self.packet({ + type: PacketType.ACK, + id: id, + data: args, + }); + }; + } + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + onack(packet) { + const ack = this.acks[packet.id]; + if ("function" === typeof ack) { + ack.apply(this, packet.data); + delete this.acks[packet.id]; + } + else { + } + } + /** + * Called upon server connect. + * + * @private + */ + onconnect(id) { + this.id = id; + this.connected = true; + this.emitBuffered(); + this.emitReserved("connect"); + } + /** + * Emit buffered events (received and emitted). + * + * @private + */ + emitBuffered() { + this.receiveBuffer.forEach((args) => this.emitEvent(args)); + this.receiveBuffer = []; + this.sendBuffer.forEach((packet) => { + this.notifyOutgoingListeners(packet); + this.packet(packet); + }); + this.sendBuffer = []; + } + /** + * Called upon server disconnect. + * + * @private + */ + ondisconnect() { + this.destroy(); + this.onclose("io server disconnect"); + } + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + destroy() { + if (this.subs) { + // clean subscriptions to avoid reconnections + this.subs.forEach((subDestroy) => subDestroy()); + this.subs = undefined; + } + this.io["_destroy"](this); + } + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + disconnect() { + if (this.connected) { + this.packet({ type: PacketType.DISCONNECT }); + } + // remove socket from pool + this.destroy(); + if (this.connected) { + // fire events + this.onclose("io client disconnect"); + } + return this; + } + /** + * Alias for disconnect() + * + * @return self + * @public + */ + close() { + return this.disconnect(); + } + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + compress(compress) { + this.flags.compress = compress; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + get volatile() { + this.flags.volatile = true; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + timeout(timeout) { + this.flags.timeout = timeout; + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + onAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + prependAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + offAny(listener) { + if (!this._anyListeners) { + return this; + } + if (listener) { + const listeners = this._anyListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAny() { + return this._anyListeners || []; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+     *
+     * socket.onAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + onAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+     *
+     * socket.prependAnyOutgoing((event, ...args) => {
+     *   console.log(event);
+     * });
+     *
+     * 
+ * + * @public + */ + prependAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+     *
+     * const handler = (event, ...args) => {
+     *   console.log(event);
+     * }
+     *
+     * socket.onAnyOutgoing(handler);
+     *
+     * // then later
+     * socket.offAnyOutgoing(handler);
+     *
+     * 
+ * + * @public + */ + offAnyOutgoing(listener) { + if (!this._anyOutgoingListeners) { + return this; + } + if (listener) { + const listeners = this._anyOutgoingListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyOutgoingListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + listenersAnyOutgoing() { + return this._anyOutgoingListeners || []; + } + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + notifyOutgoingListeners(packet) { + if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { + const listeners = this._anyOutgoingListeners.slice(); + for (const listener of listeners) { + listener.apply(this, packet.data); + } + } + } +} diff --git a/node_modules/socket.io-client/build/esm/url.d.ts b/node_modules/socket.io-client/build/esm/url.d.ts new file mode 100644 index 0000000..d2d669e --- /dev/null +++ b/node_modules/socket.io-client/build/esm/url.d.ts @@ -0,0 +1,33 @@ +declare type ParsedUrl = { + source: string; + protocol: string; + authority: string; + userInfo: string; + user: string; + password: string; + host: string; + port: string; + relative: string; + path: string; + directory: string; + file: string; + query: string; + anchor: string; + pathNames: Array; + queryKey: { + [key: string]: string; + }; + id: string; + href: string; +}; +/** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ +export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl; +export {}; diff --git a/node_modules/socket.io-client/build/esm/url.js b/node_modules/socket.io-client/build/esm/url.js new file mode 100644 index 0000000..0bc494e --- /dev/null +++ b/node_modules/socket.io-client/build/esm/url.js @@ -0,0 +1,59 @@ +import { parse } from "engine.io-client"; +/** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ +export function url(uri, path = "", loc) { + let obj = uri; + // default to window.location + loc = loc || (typeof location !== "undefined" && location); + if (null == uri) + uri = loc.protocol + "//" + loc.host; + // relative path support + if (typeof uri === "string") { + if ("/" === uri.charAt(0)) { + if ("/" === uri.charAt(1)) { + uri = loc.protocol + uri; + } + else { + uri = loc.host + uri; + } + } + if (!/^(https?|wss?):\/\//.test(uri)) { + if ("undefined" !== typeof loc) { + uri = loc.protocol + "//" + uri; + } + else { + uri = "https://" + uri; + } + } + // parse + obj = parse(uri); + } + // make sure we treat `localhost:80` and `localhost` equally + if (!obj.port) { + if (/^(http|ws)$/.test(obj.protocol)) { + obj.port = "80"; + } + else if (/^(http|ws)s$/.test(obj.protocol)) { + obj.port = "443"; + } + } + obj.path = obj.path || "/"; + const ipv6 = obj.host.indexOf(":") !== -1; + const host = ipv6 ? "[" + obj.host + "]" : obj.host; + // define unique id + obj.id = obj.protocol + "://" + host + ":" + obj.port + path; + // define href + obj.href = + obj.protocol + + "://" + + host + + (loc && loc.port === obj.port ? "" : ":" + obj.port); + return obj; +} diff --git a/node_modules/socket.io-client/dist/socket.io.esm.min.js b/node_modules/socket.io-client/dist/socket.io.esm.min.js new file mode 100644 index 0000000..9333764 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.esm.min.js @@ -0,0 +1,7 @@ +/*! + * Socket.IO v4.5.1 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach((s=>{e[t[s]]=s}));const s={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=({type:e,data:s},r,a)=>{return n&&s instanceof Blob?r?a(s):o(s,a):i&&(s instanceof ArrayBuffer||(h=s,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(h):h&&h.buffer instanceof ArrayBuffer))?r?a(s):o(new Blob([s]),a):a(t[e]+(s||""));var h},o=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+t)},s.readAsDataURL(t)};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="undefined"==typeof Uint8Array?[]:new Uint8Array(256),c=0;c{if("string"!=typeof t)return{type:"message",data:d(t,n)};const i=t.charAt(0);if("b"===i)return{type:"message",data:l(t.substring(1),n)};return e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:s},l=(t,e)=>{if(p){const s=function(t){var e,s,n,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);var p=new ArrayBuffer(o),u=new Uint8Array(p);for(e=0;e>4,u[c++]=(15&n)<<4|i>>2,u[c++]=(3&i)<<6|63&r;return p}(t);return d(s,e)}return{base64:!0,data:t}},d=(t,e)=>"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t,f=String.fromCharCode(30);function y(t){if(t)return function(t){for(var e in y.prototype)t[e]=y.prototype[e];return t}(t)}y.prototype.on=y.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},y.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},y.prototype.off=y.prototype.removeListener=y.prototype.removeAllListeners=y.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}const b=setTimeout,v=clearTimeout;function k(t,e){e.useNativeTimers?(t.setTimeoutFn=b.bind(g),t.clearTimeoutFn=v.bind(g)):(t.setTimeoutFn=setTimeout.bind(g),t.clearTimeoutFn=clearTimeout.bind(g))}class w extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class _ extends y{constructor(t){super(),this.writable=!1,k(this,t),this.opts=t,this.query=t.query,this.readyState="",this.socket=t.socket}onError(t,e,s){return super.emitReserved("error",new w(t,e,s)),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=u(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}}const E="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),A={};let R,O=0,C=0;function T(t){let e="";do{e=E[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function B(){const t=T(+new Date);return t!==R?(O=0,R=t):t+"."+T(O++)}for(;C<64;C++)A[E[C]]=C;function N(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const S=x;function L(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||S))return new XMLHttpRequest}catch(t){}if(!e)try{return new(g[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function P(){}const j=null!=new L({xdomain:!1}).responseType;class q extends y{constructor(t,e){super(),k(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.create()}create(){const t=m(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;const e=this.xhr=new L(t);try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&e.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),e.onreadystatechange=()=>{4===e.readyState&&(200===e.status||1223===e.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=q.requestsCount++,q.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=P,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete q.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(q.requestsCount=0,q.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",I);else if("function"==typeof addEventListener){addEventListener("onpagehide"in g?"pagehide":"unload",I,!1)}function I(){for(let t in q.requests)q.requests.hasOwnProperty(t)&&q.requests[t].abort()}const D="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),F=g.WebSocket||g.MozWebSocket,M="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class U extends _{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,s=M?{}:m(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=M?new F(t,e,s):e?new F(t,e):new F(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e{try{this.ws.send(t)}catch(t){}n&&D((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let s="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(s=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=B()),this.supportsBinary||(t.b64=1);const n=N(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+s+this.opts.path+(n.length?"?"+n:"")}check(){return!(!F||"__initialize"in F&&this.name===U.prototype.name)}}const V={websocket:U,polling:class extends _{constructor(t){if(super(t),this.polling=!1,"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port,this.xs=t.secure!==e}const e=t&&t.forceBase64;this.supportsBinary=j&&!e}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(f),n=[];for(let t=0;t{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,n=new Array(s);let i=0;t.forEach(((t,o)=>{r(t,!1,(t=>{n[o]=t,++i===s&&e(n.join(f))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let t=this.query||{};const e=this.opts.secure?"https":"http";let s="";!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=B()),this.supportsBinary||t.sid||(t.b64=1),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(s=":"+this.opts.port);const n=N(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+s+this.opts.path+(n.length?"?"+n:"")}request(t={}){return Object.assign(t,{xd:this.xd,xs:this.xs},this.opts),new q(this.uri(),t)}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",((t,e)=>{this.onError("xhr post error",t,e)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",((t,e)=>{this.onError("xhr poll error",t,e)})),this.pollXhr=t}}},H=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,K=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y(t){const e=t,s=t.indexOf("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let i=H.exec(t||""),r={},o=14;for(;o--;)r[K[o]]=i[o]||"";return-1!=s&&-1!=n&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=/\/{2,9}/g,n=e.replace(s,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1);"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(s[e]=n)})),s}(0,r.query),r}class z extends y{constructor(t,e={}){super(),t&&"object"==typeof t&&(e=t,t=null),t?(t=Y(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=Y(e.host).host),k(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,n=s.length;t{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new V[t](s)}open(){let t;if(this.opts.rememberUpgrade&&z.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(t=>this.onClose("transport close",t)))}probe(t){let e=this.createTransport(t),s=!1;z.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;z.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function i(){s||(s=!0,c(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function h(t){e&&t.name!==e.name&&i()}const c=()=>{e.removeListener("open",n),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",h)};e.once("open",n),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",h),e.open()}onOpen(){if(this.readyState="open",z.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let t=0;const e=this.upgrades.length;for(;t{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s=57344?s+=3:(n++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}write(t,e,s){return this.sendPacket("message",t,e,s),this}send(t,e,s){return this.sendPacket("message",t,e,s),this}sendPacket(t,e,s,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}onError(t){z.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let s=0;const n=t.length;for(;s"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||J&&t instanceof Blob||X&&t instanceof File}function Q(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e0;case it.ACK:case it.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class ot{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=et(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var at=Object.freeze({__proto__:null,protocol:5,get PacketType(){return it},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==it.EVENT&&t.type!==it.ACK||!Q(t)?[this.encodeAsString(t)]:(t.type=t.type===it.EVENT?it.BINARY_EVENT:it.BINARY_ACK,this.encodeAsBinary(t))}encodeAsString(t){let e=""+t.type;return t.type!==it.BINARY_EVENT&&t.type!==it.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Z(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}},Decoder:rt});function ht(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const ct=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pt extends y{constructor(t,e,s){super(),this.connected=!1,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[ht(t,"open",this.onopen.bind(this)),ht(t,"packet",this.onpacket.bind(this)),ht(t,"error",this.onerror.bind(this)),ht(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(ct.hasOwnProperty(t))throw new Error('"'+t+'" is a reserved event name');e.unshift(t);const s={type:it.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){const s=this.flags.timeout;if(void 0===s)return void(this.acks[t]=e);const n=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e{this.io.clearTimeoutFn(n),e.apply(this,[null,...t])}}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this.packet({type:it.CONNECT,data:t})})):this.packet({type:it.CONNECT,data:this.auth})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case it.CONNECT:if(t.data&&t.data.sid){const e=t.data.sid;this.onconnect(e)}else this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case it.EVENT:case it.BINARY_EVENT:this.onevent(t);break;case it.ACK:case it.BINARY_ACK:this.onack(t);break;case it.DISCONNECT:this.ondisconnect();break;case it.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t)}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:it.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])}onconnect(t){this.id=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>{this.notifyOutgoingListeners(t),this.packet(t)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:it.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s0&&t.jitter<=1?t.jitter:0,this.attempts=0}ut.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-s:t+s}return 0|Math.min(t,this.max)},ut.prototype.reset=function(){this.attempts=0},ut.prototype.setMin=function(t){this.ms=t},ut.prototype.setMax=function(t){this.max=t},ut.prototype.setJitter=function(t){this.jitter=t};class lt extends y{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,k(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new ut({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||at;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new z(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=ht(e,"open",(function(){s.onopen(),t&&t()})),i=ht(e,"error",(e=>{s.cleanup(),s._readyState="closed",this.emitReserved("error",e),t?t(e):s.maybeReconnectOnOpen()}));if(!1!==this._timeout){const t=this._timeout;0===t&&n();const s=this.setTimeoutFn((()=>{n(),e.close(),e.emit("error",new Error("timeout"))}),t);this.opts.autoUnref&&s.unref(),this.subs.push((function(){clearTimeout(s)}))}return this.subs.push(n),this.subs.push(i),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(ht(t,"ping",this.onping.bind(this)),ht(t,"data",this.ondata.bind(this)),ht(t,"error",this.onerror.bind(this)),ht(t,"close",this.onclose.bind(this)),ht(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){this.decoder.add(t)}ondecoded(t){this.emitReserved("packet",t)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s||(s=new pt(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;st())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&s.unref(),this.subs.push((function(){clearTimeout(s)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const dt={};function ft(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let n=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),n=Y(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,i=s.id,r=s.path,o=dt[i]&&r in dt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new lt(n,e):(dt[i]||(dt[i]=new lt(n,e)),a=dt[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(ft,{Manager:lt,Socket:pt,io:ft,connect:ft});export{lt as Manager,pt as Socket,ft as connect,ft as default,ft as io,nt as protocol}; +//# sourceMappingURL=socket.io.esm.min.js.map diff --git a/node_modules/socket.io-client/dist/socket.io.esm.min.js.map b/node_modules/socket.io-client/dist/socket.io.esm.min.js.map new file mode 100644 index 0000000..798f84f --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.esm.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socket.io.esm.min.js","sources":["../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/commons.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/encodePacket.browser.js","../node_modules/@socket.io/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/decodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/index.js","../node_modules/@socket.io/component-emitter/index.mjs","../node_modules/engine.io-client/build/esm/globalThis.browser.js","../node_modules/engine.io-client/build/esm/util.js","../node_modules/engine.io-client/build/esm/transport.js","../node_modules/engine.io-client/build/esm/contrib/yeast.js","../node_modules/engine.io-client/build/esm/contrib/parseqs.js","../node_modules/engine.io-client/build/esm/contrib/has-cors.js","../node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js","../node_modules/engine.io-client/build/esm/transports/polling.js","../node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js","../node_modules/engine.io-client/build/esm/transports/websocket.js","../node_modules/engine.io-client/build/esm/transports/index.js","../node_modules/engine.io-client/build/esm/contrib/parseuri.js","../node_modules/engine.io-client/build/esm/socket.js","../node_modules/socket.io-parser/build/esm/is-binary.js","../node_modules/socket.io-parser/build/esm/binary.js","../node_modules/socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export default (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import globalThis from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport globalThis from \"../globalThis.js\";\nexport default function (opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport XMLHttpRequest from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport globalThis from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import globalThis from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return (!!WebSocket &&\n !(\"__initialize\" in WebSocket && this.name === WS.prototype.name));\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","const withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n (typeof File !== \"undefined\" &&\n toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nexport function isBinary(obj) {\n return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n (withNativeBlob && obj instanceof Blob) ||\n (withNativeFile && obj instanceof File));\n}\nexport function hasBinary(obj, toJSON) {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n if (Array.isArray(obj)) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (hasBinary(obj[i])) {\n return true;\n }\n }\n return false;\n }\n if (isBinary(obj)) {\n return true;\n }\n if (obj.toJSON &&\n typeof obj.toJSON === \"function\" &&\n arguments.length === 1) {\n return hasBinary(obj.toJSON(), true);\n }\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n return true;\n }\n }\n return false;\n}\n","import { isBinary } from \"./is-binary.js\";\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nexport function deconstructPacket(packet) {\n const buffers = [];\n const packetData = packet.data;\n const pack = packet;\n pack.data = _deconstructPacket(packetData, buffers);\n pack.attachments = buffers.length; // number of binary 'attachments'\n return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (isBinary(data)) {\n const placeholder = { _placeholder: true, num: buffers.length };\n buffers.push(data);\n return placeholder;\n }\n else if (Array.isArray(data)) {\n const newData = new Array(data.length);\n for (let i = 0; i < data.length; i++) {\n newData[i] = _deconstructPacket(data[i], buffers);\n }\n return newData;\n }\n else if (typeof data === \"object\" && !(data instanceof Date)) {\n const newData = {};\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n newData[key] = _deconstructPacket(data[key], buffers);\n }\n }\n return newData;\n }\n return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nexport function reconstructPacket(packet, buffers) {\n packet.data = _reconstructPacket(packet.data, buffers);\n packet.attachments = undefined; // no longer useful\n return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (data && data._placeholder) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n }\n else if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n }\n else if (typeof data === \"object\") {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n }\n return data;\n}\n","import { Emitter } from \"@socket.io/component-emitter\";\nimport { deconstructPacket, reconstructPacket } from \"./binary.js\";\nimport { isBinary, hasBinary } from \"./is-binary.js\";\n/**\n * Protocol version.\n *\n * @public\n */\nexport const protocol = 5;\nexport var PacketType;\n(function (PacketType) {\n PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nexport class Encoder {\n /**\n * Encoder constructor\n *\n * @param {function} replacer - custom replacer to pass down to JSON.parse\n */\n constructor(replacer) {\n this.replacer = replacer;\n }\n /**\n * Encode a packet as a single string if non-binary, or as a\n * buffer sequence, depending on packet type.\n *\n * @param {Object} obj - packet object\n */\n encode(obj) {\n if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n if (hasBinary(obj)) {\n obj.type =\n obj.type === PacketType.EVENT\n ? PacketType.BINARY_EVENT\n : PacketType.BINARY_ACK;\n return this.encodeAsBinary(obj);\n }\n }\n return [this.encodeAsString(obj)];\n }\n /**\n * Encode packet as string.\n */\n encodeAsString(obj) {\n // first is type\n let str = \"\" + obj.type;\n // attachments if we have them\n if (obj.type === PacketType.BINARY_EVENT ||\n obj.type === PacketType.BINARY_ACK) {\n str += obj.attachments + \"-\";\n }\n // if we have a namespace other than `/`\n // we append it followed by a comma `,`\n if (obj.nsp && \"/\" !== obj.nsp) {\n str += obj.nsp + \",\";\n }\n // immediately followed by the id\n if (null != obj.id) {\n str += obj.id;\n }\n // json data\n if (null != obj.data) {\n str += JSON.stringify(obj.data, this.replacer);\n }\n return str;\n }\n /**\n * Encode packet as 'buffer sequence' by removing blobs, and\n * deconstructing packet into object with placeholders and\n * a list of buffers.\n */\n encodeAsBinary(obj) {\n const deconstruction = deconstructPacket(obj);\n const pack = this.encodeAsString(deconstruction.packet);\n const buffers = deconstruction.buffers;\n buffers.unshift(pack); // add packet info to beginning of data list\n return buffers; // write all the buffers\n }\n}\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nexport class Decoder extends Emitter {\n /**\n * Decoder constructor\n *\n * @param {function} reviver - custom reviver to pass down to JSON.stringify\n */\n constructor(reviver) {\n super();\n this.reviver = reviver;\n }\n /**\n * Decodes an encoded packet string into packet JSON.\n *\n * @param {String} obj - encoded packet\n */\n add(obj) {\n let packet;\n if (typeof obj === \"string\") {\n packet = this.decodeString(obj);\n if (packet.type === PacketType.BINARY_EVENT ||\n packet.type === PacketType.BINARY_ACK) {\n // binary packet's json\n this.reconstructor = new BinaryReconstructor(packet);\n // no attachments, labeled binary but no binary data to follow\n if (packet.attachments === 0) {\n super.emitReserved(\"decoded\", packet);\n }\n }\n else {\n // non-binary full packet\n super.emitReserved(\"decoded\", packet);\n }\n }\n else if (isBinary(obj) || obj.base64) {\n // raw binary data\n if (!this.reconstructor) {\n throw new Error(\"got binary data when not reconstructing a packet\");\n }\n else {\n packet = this.reconstructor.takeBinaryData(obj);\n if (packet) {\n // received final buffer\n this.reconstructor = null;\n super.emitReserved(\"decoded\", packet);\n }\n }\n }\n else {\n throw new Error(\"Unknown type: \" + obj);\n }\n }\n /**\n * Decode a packet String (JSON data)\n *\n * @param {String} str\n * @return {Object} packet\n */\n decodeString(str) {\n let i = 0;\n // look up type\n const p = {\n type: Number(str.charAt(0)),\n };\n if (PacketType[p.type] === undefined) {\n throw new Error(\"unknown packet type \" + p.type);\n }\n // look up attachments if type binary\n if (p.type === PacketType.BINARY_EVENT ||\n p.type === PacketType.BINARY_ACK) {\n const start = i + 1;\n while (str.charAt(++i) !== \"-\" && i != str.length) { }\n const buf = str.substring(start, i);\n if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n throw new Error(\"Illegal attachments\");\n }\n p.attachments = Number(buf);\n }\n // look up namespace (if any)\n if (\"/\" === str.charAt(i + 1)) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (\",\" === c)\n break;\n if (i === str.length)\n break;\n }\n p.nsp = str.substring(start, i);\n }\n else {\n p.nsp = \"/\";\n }\n // look up id\n const next = str.charAt(i + 1);\n if (\"\" !== next && Number(next) == next) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (null == c || Number(c) != c) {\n --i;\n break;\n }\n if (i === str.length)\n break;\n }\n p.id = Number(str.substring(start, i + 1));\n }\n // look up json data\n if (str.charAt(++i)) {\n const payload = this.tryParse(str.substr(i));\n if (Decoder.isPayloadValid(p.type, payload)) {\n p.data = payload;\n }\n else {\n throw new Error(\"invalid payload\");\n }\n }\n return p;\n }\n tryParse(str) {\n try {\n return JSON.parse(str, this.reviver);\n }\n catch (e) {\n return false;\n }\n }\n static isPayloadValid(type, payload) {\n switch (type) {\n case PacketType.CONNECT:\n return typeof payload === \"object\";\n case PacketType.DISCONNECT:\n return payload === undefined;\n case PacketType.CONNECT_ERROR:\n return typeof payload === \"string\" || typeof payload === \"object\";\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n return Array.isArray(payload) && payload.length > 0;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n return Array.isArray(payload);\n }\n }\n /**\n * Deallocates a parser's resources\n */\n destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }\n}\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n constructor(packet) {\n this.packet = packet;\n this.buffers = [];\n this.reconPack = packet;\n }\n /**\n * Method to be called when binary data received from connection\n * after a BINARY_EVENT packet.\n *\n * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n * @return {null | Object} returns null if more binary data is expected or\n * a reconstructed packet object if all buffers have been received.\n */\n takeBinaryData(binData) {\n this.buffers.push(binData);\n if (this.buffers.length === this.reconPack.attachments) {\n // done with buffer list\n const packet = reconstructPacket(this.reconPack, this.buffers);\n this.finishedReconstruction();\n return packet;\n }\n return null;\n }\n /**\n * Cleans up binary packet reconstruction variables.\n */\n finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }\n}\n","export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n","import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n *\n * @public\n */\n constructor(io, nsp, opts) {\n super();\n this.connected = false;\n this.receiveBuffer = [];\n this.sendBuffer = [];\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @public\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for connect()\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * @return self\n * @public\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @return self\n * @public\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev + '\" is a reserved event name');\n }\n args.unshift(ev);\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n const timeout = this.flags.timeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: PacketType.CONNECT, data: this.auth });\n }\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n const id = packet.data.sid;\n this.onconnect(id);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id) {\n this.id = id;\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually.\n *\n * @return self\n * @public\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for disconnect()\n *\n * @return self\n * @public\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n * @public\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @returns self\n * @public\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * ```\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n * ```\n *\n * @returns self\n * @public\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n * @public\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n * @public\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n * @public\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n *\n *
\n     *\n     * socket.onAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n *\n *
\n     *\n     * socket.prependAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n *\n *
\n     *\n     * const handler = (event, ...args) => {\n     *   console.log(event);\n     * }\n     *\n     * socket.onAnyOutgoing(handler);\n     *\n     * // then later\n     * socket.offAnyOutgoing(handler);\n     *\n     * 
\n *\n * @public\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n","/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n","import { Socket as Engine, installTimerFunctions, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n this.decoder.add(data);\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n this.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n","import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n","import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","encodePacket","supportsBinary","callback","encodeBlobAsBase64","obj","isView","buffer","fileReader","FileReader","onload","content","result","split","readAsDataURL","chars","lookup","Uint8Array","i","length","charCodeAt","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","decoded","base64","encoded1","encoded2","encoded3","encoded4","bufferLength","len","p","arraybuffer","bytes","decode","SEPARATOR","String","fromCharCode","Emitter","mixin","on","addEventListener","event","fn","this","_callbacks","push","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","cb","callbacks","splice","emit","args","Array","slice","emitReserved","listeners","hasListeners","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","TransportError","Error","constructor","reason","description","context","super","Transport","writable","query","readyState","socket","onError","open","doOpen","close","doClose","onClose","send","packets","write","onOpen","onData","packet","onPacket","details","alphabet","map","prev","seed","encode","num","encoded","Math","floor","yeast","now","Date","str","encodeURIComponent","value","XMLHttpRequest","err","hasCORS","xdomain","e","concat","join","empty","hasXHR2","responseType","Request","uri","method","async","undefined","xd","xscheme","xs","xhr","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","onLoad","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","nextTick","Promise","resolve","then","WebSocket","MozWebSocket","isReactNative","navigator","product","toLowerCase","WS","forceBase64","name","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","schema","secure","port","Number","timestampRequests","timestampParam","b64","encodedQuery","hostname","indexOf","path","transports","websocket","polling","location","isSSL","protocol","poll","pause","onPause","total","doPoll","encodedPayload","encodedPackets","decodedPacket","decodePayload","count","encodePayload","doWrite","sid","request","assign","req","xhrStatus","pollXhr","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","regx","names","substr","queryKey","$0","$1","$2","Socket","writeBuffer","prevBufferLen","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","qs","qry","pairs","l","pair","decodeURIComponent","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","createTransport","EIO","priorWebsocketSuccess","shift","setTransport","onDrain","probe","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","payloadSize","c","utf8Length","ceil","byteLength","size","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j","withNativeFile","File","isBinary","hasBinary","toJSON","isArray","deconstructPacket","buffers","packetData","pack","_deconstructPacket","attachments","placeholder","_placeholder","newData","reconstructPacket","_reconstructPacket","PacketType","Decoder","reviver","add","decodeString","BINARY_EVENT","BINARY_ACK","reconstructor","BinaryReconstructor","takeBinaryData","start","buf","nsp","next","payload","tryParse","isPayloadValid","static","CONNECT","DISCONNECT","CONNECT_ERROR","EVENT","ACK","destroy","finishedReconstruction","reconPack","binData","replacer","encodeAsString","encodeAsBinary","stringify","deconstruction","unshift","RESERVED_EVENTS","freeze","connect","connect_error","disconnect","disconnecting","newListener","io","connected","receiveBuffer","sendBuffer","ids","acks","flags","auth","_autoConnect","disconnected","subEvents","subs","onpacket","active","_readyState","ack","pop","_registerAckCallback","isTransportWritable","engine","volatile","notifyOutgoingListeners","timer","_packet","onconnect","onevent","onack","ondisconnect","message","emitEvent","_anyListeners","listener","sent","emitBuffered","subDestroy","onAny","prependAny","offAny","listenersAny","onAnyOutgoing","_anyOutgoingListeners","prependAnyOutgoing","offAnyOutgoing","listenersAnyOutgoing","Backoff","ms","min","max","factor","jitter","attempts","duration","pow","rand","random","deviation","reset","setMin","setMax","setJitter","Manager","_a","nsps","reconnection","reconnectionAttempts","Infinity","reconnectionDelay","reconnectionDelayMax","randomizationFactor","backoff","_parser","parser","encoder","Encoder","decoder","autoConnect","v","_reconnection","_reconnectionAttempts","_reconnectionDelay","_randomizationFactor","_reconnectionDelayMax","_timeout","maybeReconnectOnOpen","_reconnecting","reconnect","Engine","skipReconnect","openSubDestroy","errorSub","onping","ondata","ondecoded","_destroy","_close","delay","onreconnect","attempt","cache","parsed","loc","test","href","url","sameNamespace","forceNew","multiplex"],"mappings":";;;;;AAAA,MAAMA,EAAeC,OAAOC,OAAO,MACnCF,EAAmB,KAAI,IACvBA,EAAoB,MAAI,IACxBA,EAAmB,KAAI,IACvBA,EAAmB,KAAI,IACvBA,EAAsB,QAAI,IAC1BA,EAAsB,QAAI,IAC1BA,EAAmB,KAAI,IACvB,MAAMG,EAAuBF,OAAOC,OAAO,MAC3CD,OAAOG,KAAKJ,GAAcK,SAAQC,IAC9BH,EAAqBH,EAAaM,IAAQA,KAE9C,MAAMC,EAAe,CAAEC,KAAM,QAASC,KAAM,gBCXtCC,EAAiC,mBAATC,MACT,oBAATA,MACqC,6BAAzCV,OAAOW,UAAUC,SAASC,KAAKH,MACjCI,EAA+C,mBAAhBC,YAO/BC,EAAe,EAAGT,KAAAA,EAAMC,KAAAA,GAAQS,EAAgBC,KAClD,OAAIT,GAAkBD,aAAgBE,KAC9BO,EACOC,EAASV,GAGTW,EAAmBX,EAAMU,GAG/BJ,IACJN,aAAgBO,cAfVK,EAegCZ,EAdN,mBAAvBO,YAAYM,OACpBN,YAAYM,OAAOD,GACnBA,GAAOA,EAAIE,kBAAkBP,cAa3BE,EACOC,EAASV,GAGTW,EAAmB,IAAIT,KAA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/socket.io.js new file mode 100644 index 0000000..aaba9a8 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.js @@ -0,0 +1,4440 @@ +/*! + * Socket.IO v4.5.1 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); + } + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); + } + + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); + } + + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; + } + + function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return _assertThisInitialized(self); + } + + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return _possibleConstructorReturn(this, result); + }; + } + + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + + return object; + } + + function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); + } + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; + } + + function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function () {}; + + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = it.call(o); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; + } + + var PACKET_TYPES = Object.create(null); // no Map = no polyfill + + PACKET_TYPES["open"] = "0"; + PACKET_TYPES["close"] = "1"; + PACKET_TYPES["ping"] = "2"; + PACKET_TYPES["pong"] = "3"; + PACKET_TYPES["message"] = "4"; + PACKET_TYPES["upgrade"] = "5"; + PACKET_TYPES["noop"] = "6"; + var PACKET_TYPES_REVERSE = Object.create(null); + Object.keys(PACKET_TYPES).forEach(function (key) { + PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; + }); + var ERROR_PACKET = { + type: "error", + data: "parser error" + }; + + var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]"; + var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10 + + var isView$1 = function isView(obj) { + return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer; + }; + + var encodePacket = function encodePacket(_ref, supportsBinary, callback) { + var type = _ref.type, + data = _ref.data; + + if (withNativeBlob$1 && data instanceof Blob) { + if (supportsBinary) { + return callback(data); + } else { + return encodeBlobAsBase64(data, callback); + } + } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) { + if (supportsBinary) { + return callback(data); + } else { + return encodeBlobAsBase64(new Blob([data]), callback); + } + } // plain string + + + return callback(PACKET_TYPES[type] + (data || "")); + }; + + var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) { + var fileReader = new FileReader(); + + fileReader.onload = function () { + var content = fileReader.result.split(",")[1]; + callback("b" + content); + }; + + return fileReader.readAsDataURL(data); + }; + + /* + * base64-arraybuffer 1.0.1 + * Copyright (c) 2022 Niklas von Hertzen + * Released under MIT License + */ + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index. + + var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); + + for (var i$1 = 0; i$1 < chars.length; i$1++) { + lookup$1[chars.charCodeAt(i$1)] = i$1; + } + + var decode$1 = function decode(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, + i, + p = 0, + encoded1, + encoded2, + encoded3, + encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (i = 0; i < len; i += 4) { + encoded1 = lookup$1[base64.charCodeAt(i)]; + encoded2 = lookup$1[base64.charCodeAt(i + 1)]; + encoded3 = lookup$1[base64.charCodeAt(i + 2)]; + encoded4 = lookup$1[base64.charCodeAt(i + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; + }; + + var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function"; + + var decodePacket = function decodePacket(encodedPacket, binaryType) { + if (typeof encodedPacket !== "string") { + return { + type: "message", + data: mapBinary(encodedPacket, binaryType) + }; + } + + var type = encodedPacket.charAt(0); + + if (type === "b") { + return { + type: "message", + data: decodeBase64Packet(encodedPacket.substring(1), binaryType) + }; + } + + var packetType = PACKET_TYPES_REVERSE[type]; + + if (!packetType) { + return ERROR_PACKET; + } + + return encodedPacket.length > 1 ? { + type: PACKET_TYPES_REVERSE[type], + data: encodedPacket.substring(1) + } : { + type: PACKET_TYPES_REVERSE[type] + }; + }; + + var decodeBase64Packet = function decodeBase64Packet(data, binaryType) { + if (withNativeArrayBuffer$1) { + var decoded = decode$1(data); + return mapBinary(decoded, binaryType); + } else { + return { + base64: true, + data: data + }; // fallback for old browsers + } + }; + + var mapBinary = function mapBinary(data, binaryType) { + switch (binaryType) { + case "blob": + return data instanceof ArrayBuffer ? new Blob([data]) : data; + + case "arraybuffer": + default: + return data; + // assuming the data is already an ArrayBuffer + } + }; + + var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text + + var encodePayload = function encodePayload(packets, callback) { + // some packets may be added to the array while encoding, so the initial length must be saved + var length = packets.length; + var encodedPackets = new Array(length); + var count = 0; + packets.forEach(function (packet, i) { + // force base64 encoding for binary packets + encodePacket(packet, false, function (encodedPacket) { + encodedPackets[i] = encodedPacket; + + if (++count === length) { + callback(encodedPackets.join(SEPARATOR)); + } + }); + }); + }; + + var decodePayload = function decodePayload(encodedPayload, binaryType) { + var encodedPackets = encodedPayload.split(SEPARATOR); + var packets = []; + + for (var i = 0; i < encodedPackets.length; i++) { + var decodedPacket = decodePacket(encodedPackets[i], binaryType); + packets.push(decodedPacket); + + if (decodedPacket.type === "error") { + break; + } + } + + return packets; + }; + + var protocol$1 = 4; + + /** + * Initialize a new `Emitter`. + * + * @api public + */ + function Emitter(obj) { + if (obj) return mixin(obj); + } + /** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + + return obj; + } + /** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) { + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn); + return this; + }; + /** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.once = function (event, fn) { + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; + }; + /** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + + + Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) { + this._callbacks = this._callbacks || {}; // all + + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } // specific event + + + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; // remove all handlers + + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } // remove specific handler + + + var cb; + + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + + + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; + }; + /** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + + + Emitter.prototype.emit = function (event) { + this._callbacks = this._callbacks || {}; + var args = new Array(arguments.length - 1), + callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; + }; // alias used for reserved events (protected method) + + + Emitter.prototype.emitReserved = Emitter.prototype.emit; + /** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + + Emitter.prototype.listeners = function (event) { + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; + }; + /** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + + + Emitter.prototype.hasListeners = function (event) { + return !!this.listeners(event).length; + }; + + var globalThis = (function () { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else { + return Function("return this")(); + } + })(); + + function pick(obj) { + for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + attr[_key - 1] = arguments[_key]; + } + + return attr.reduce(function (acc, k) { + if (obj.hasOwnProperty(k)) { + acc[k] = obj[k]; + } + + return acc; + }, {}); + } // Keep a reference to the real timeout functions so they can be used when overridden + + var NATIVE_SET_TIMEOUT = setTimeout; + var NATIVE_CLEAR_TIMEOUT = clearTimeout; + function installTimerFunctions(obj, opts) { + if (opts.useNativeTimers) { + obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis); + obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis); + } else { + obj.setTimeoutFn = setTimeout.bind(globalThis); + obj.clearTimeoutFn = clearTimeout.bind(globalThis); + } + } // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) + + var BASE64_OVERHEAD = 1.33; // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 + + function byteLength(obj) { + if (typeof obj === "string") { + return utf8Length(obj); + } // arraybuffer or blob + + + return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); + } + + function utf8Length(str) { + var c = 0, + length = 0; + + for (var i = 0, l = str.length; i < l; i++) { + c = str.charCodeAt(i); + + if (c < 0x80) { + length += 1; + } else if (c < 0x800) { + length += 2; + } else if (c < 0xd800 || c >= 0xe000) { + length += 3; + } else { + i++; + length += 4; + } + } + + return length; + } + + var TransportError = /*#__PURE__*/function (_Error) { + _inherits(TransportError, _Error); + + var _super = _createSuper(TransportError); + + function TransportError(reason, description, context) { + var _this; + + _classCallCheck(this, TransportError); + + _this = _super.call(this, reason); + _this.description = description; + _this.context = context; + _this.type = "TransportError"; + return _this; + } + + return TransportError; + }( /*#__PURE__*/_wrapNativeSuper(Error)); + + var Transport = /*#__PURE__*/function (_Emitter) { + _inherits(Transport, _Emitter); + + var _super2 = _createSuper(Transport); + + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + function Transport(opts) { + var _this2; + + _classCallCheck(this, Transport); + + _this2 = _super2.call(this); + _this2.writable = false; + installTimerFunctions(_assertThisInitialized(_this2), opts); + _this2.opts = opts; + _this2.query = opts.query; + _this2.readyState = ""; + _this2.socket = opts.socket; + return _this2; + } + /** + * Emits an error. + * + * @param {String} reason + * @param description + * @param context - the error context + * @return {Transport} for chaining + * @api protected + */ + + + _createClass(Transport, [{ + key: "onError", + value: function onError(reason, description, context) { + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context)); + + return this; + } + /** + * Opens the transport. + * + * @api public + */ + + }, { + key: "open", + value: function open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } + + return this; + } + /** + * Closes the transport. + * + * @api public + */ + + }, { + key: "close", + value: function close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } + + return this; + } + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api public + */ + + }, { + key: "send", + value: function send(packets) { + if ("open" === this.readyState) { + this.write(packets); + } + } + /** + * Called upon open + * + * @api protected + */ + + }, { + key: "onOpen", + value: function onOpen() { + this.readyState = "open"; + this.writable = true; + + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open"); + } + /** + * Called with data. + * + * @param {String} data + * @api protected + */ + + }, { + key: "onData", + value: function onData(data) { + var packet = decodePacket(data, this.socket.binaryType); + this.onPacket(packet); + } + /** + * Called with a decoded packet. + * + * @api protected + */ + + }, { + key: "onPacket", + value: function onPacket(packet) { + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet); + } + /** + * Called upon close. + * + * @api protected + */ + + }, { + key: "onClose", + value: function onClose(details) { + this.readyState = "closed"; + + _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details); + } + }]); + + return Transport; + }(Emitter); + + // imported from https://github.com/unshiftio/yeast + + var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), + length = 64, + map = {}; + var seed = 0, + i = 0, + prev; + /** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ + + function encode$1(num) { + var encoded = ''; + + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + + return encoded; + } + /** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ + + function yeast() { + var now = encode$1(+new Date()); + if (now !== prev) return seed = 0, prev = now; + return now + '.' + encode$1(seed++); + } // + // Map each character to its index. + // + + for (; i < length; i++) { + map[alphabet[i]] = i; + } + + // imported from https://github.com/galkn/querystring + + /** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ + function encode(obj) { + var str = ''; + + for (var i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + + return str; + } + /** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ + + function decode(qs) { + var qry = {}; + var pairs = qs.split('&'); + + for (var i = 0, l = pairs.length; i < l; i++) { + var pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + + return qry; + } + + // imported from https://github.com/component/has-cors + var value = false; + + try { + value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); + } catch (err) {// if XMLHttp support is disabled in IE then it will throw + // when trying to create + } + + var hasCORS = value; + + // browser shim for xmlhttprequest module + function XMLHttpRequest$1 (opts) { + var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE + + try { + if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { + return new XMLHttpRequest(); + } + } catch (e) {} + + if (!xdomain) { + try { + return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); + } catch (e) {} + } + } + + function empty() {} + + var hasXHR2 = function () { + var xhr = new XMLHttpRequest$1({ + xdomain: false + }); + return null != xhr.responseType; + }(); + + var Polling = /*#__PURE__*/function (_Transport) { + _inherits(Polling, _Transport); + + var _super = _createSuper(Polling); + + /** + * XHR Polling constructor. + * + * @param {Object} opts + * @api public + */ + function Polling(opts) { + var _this; + + _classCallCheck(this, Polling); + + _this = _super.call(this, opts); + _this.polling = false; + + if (typeof location !== "undefined") { + var isSSL = "https:" === location.protocol; + var port = location.port; // some user agents have empty `location.port` + + if (!port) { + port = isSSL ? "443" : "80"; + } + + _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port; + _this.xs = opts.secure !== isSSL; + } + /** + * XHR supports binary + */ + + + var forceBase64 = opts && opts.forceBase64; + _this.supportsBinary = hasXHR2 && !forceBase64; + return _this; + } + /** + * Transport name. + */ + + + _createClass(Polling, [{ + key: "name", + get: function get() { + return "polling"; + } + /** + * Opens the socket (triggers polling). We write a PING message to determine + * when the transport is open. + * + * @api private + */ + + }, { + key: "doOpen", + value: function doOpen() { + this.poll(); + } + /** + * Pauses polling. + * + * @param {Function} callback upon buffers are flushed and transport is paused + * @api private + */ + + }, { + key: "pause", + value: function pause(onPause) { + var _this2 = this; + + this.readyState = "pausing"; + + var pause = function pause() { + _this2.readyState = "paused"; + onPause(); + }; + + if (this.polling || !this.writable) { + var total = 0; + + if (this.polling) { + total++; + this.once("pollComplete", function () { + --total || pause(); + }); + } + + if (!this.writable) { + total++; + this.once("drain", function () { + --total || pause(); + }); + } + } else { + pause(); + } + } + /** + * Starts polling cycle. + * + * @api public + */ + + }, { + key: "poll", + value: function poll() { + this.polling = true; + this.doPoll(); + this.emitReserved("poll"); + } + /** + * Overloads onData to detect payloads. + * + * @api private + */ + + }, { + key: "onData", + value: function onData(data) { + var _this3 = this; + + var callback = function callback(packet) { + // if its the first message we consider the transport open + if ("opening" === _this3.readyState && packet.type === "open") { + _this3.onOpen(); + } // if its a close packet, we close the ongoing requests + + + if ("close" === packet.type) { + _this3.onClose({ + description: "transport closed by the server" + }); + + return false; + } // otherwise bypass onData and handle the message + + + _this3.onPacket(packet); + }; // decode payload + + + decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing + + if ("closed" !== this.readyState) { + // if we got data we're not polling + this.polling = false; + this.emitReserved("pollComplete"); + + if ("open" === this.readyState) { + this.poll(); + } + } + } + /** + * For polling, send a close packet. + * + * @api private + */ + + }, { + key: "doClose", + value: function doClose() { + var _this4 = this; + + var close = function close() { + _this4.write([{ + type: "close" + }]); + }; + + if ("open" === this.readyState) { + close(); + } else { + // in case we're trying to close while + // handshaking is in progress (GH-164) + this.once("open", close); + } + } + /** + * Writes a packets payload. + * + * @param {Array} data packets + * @param {Function} drain callback + * @api private + */ + + }, { + key: "write", + value: function write(packets) { + var _this5 = this; + + this.writable = false; + encodePayload(packets, function (data) { + _this5.doWrite(data, function () { + _this5.writable = true; + + _this5.emitReserved("drain"); + }); + }); + } + /** + * Generates uri for connection. + * + * @api private + */ + + }, { + key: "uri", + value: function uri() { + var query = this.query || {}; + var schema = this.opts.secure ? "https" : "http"; + var port = ""; // cache busting is forced + + if (false !== this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } + + if (!this.supportsBinary && !query.sid) { + query.b64 = 1; + } // avoid port if default for schema + + + if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) { + port = ":" + this.opts.port; + } + + var encodedQuery = encode(query); + var ipv6 = this.opts.hostname.indexOf(":") !== -1; + return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : ""); + } + /** + * Creates a request. + * + * @param {String} method + * @api private + */ + + }, { + key: "request", + value: function request() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _extends(opts, { + xd: this.xd, + xs: this.xs + }, this.opts); + + return new Request(this.uri(), opts); + } + /** + * Sends data. + * + * @param {String} data to send. + * @param {Function} called upon flush. + * @api private + */ + + }, { + key: "doWrite", + value: function doWrite(data, fn) { + var _this6 = this; + + var req = this.request({ + method: "POST", + data: data + }); + req.on("success", fn); + req.on("error", function (xhrStatus, context) { + _this6.onError("xhr post error", xhrStatus, context); + }); + } + /** + * Starts a poll cycle. + * + * @api private + */ + + }, { + key: "doPoll", + value: function doPoll() { + var _this7 = this; + + var req = this.request(); + req.on("data", this.onData.bind(this)); + req.on("error", function (xhrStatus, context) { + _this7.onError("xhr poll error", xhrStatus, context); + }); + this.pollXhr = req; + } + }]); + + return Polling; + }(Transport); + var Request = /*#__PURE__*/function (_Emitter) { + _inherits(Request, _Emitter); + + var _super2 = _createSuper(Request); + + /** + * Request constructor + * + * @param {Object} options + * @api public + */ + function Request(uri, opts) { + var _this8; + + _classCallCheck(this, Request); + + _this8 = _super2.call(this); + installTimerFunctions(_assertThisInitialized(_this8), opts); + _this8.opts = opts; + _this8.method = opts.method || "GET"; + _this8.uri = uri; + _this8.async = false !== opts.async; + _this8.data = undefined !== opts.data ? opts.data : null; + + _this8.create(); + + return _this8; + } + /** + * Creates the XHR object and sends the request. + * + * @api private + */ + + + _createClass(Request, [{ + key: "create", + value: function create() { + var _this9 = this; + + var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); + opts.xdomain = !!this.opts.xd; + opts.xscheme = !!this.opts.xs; + var xhr = this.xhr = new XMLHttpRequest$1(opts); + + try { + xhr.open(this.method, this.uri, this.async); + + try { + if (this.opts.extraHeaders) { + xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); + + for (var i in this.opts.extraHeaders) { + if (this.opts.extraHeaders.hasOwnProperty(i)) { + xhr.setRequestHeader(i, this.opts.extraHeaders[i]); + } + } + } + } catch (e) {} + + if ("POST" === this.method) { + try { + xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); + } catch (e) {} + } + + try { + xhr.setRequestHeader("Accept", "*/*"); + } catch (e) {} // ie6 check + + + if ("withCredentials" in xhr) { + xhr.withCredentials = this.opts.withCredentials; + } + + if (this.opts.requestTimeout) { + xhr.timeout = this.opts.requestTimeout; + } + + xhr.onreadystatechange = function () { + if (4 !== xhr.readyState) return; + + if (200 === xhr.status || 1223 === xhr.status) { + _this9.onLoad(); + } else { + // make sure the `error` event handler that's user-set + // does not throw in the same tick and gets caught here + _this9.setTimeoutFn(function () { + _this9.onError(typeof xhr.status === "number" ? xhr.status : 0); + }, 0); + } + }; + + xhr.send(this.data); + } catch (e) { + // Need to defer since .create() is called directly from the constructor + // and thus the 'error' event can only be only bound *after* this exception + // occurs. Therefore, also, we cannot throw here at all. + this.setTimeoutFn(function () { + _this9.onError(e); + }, 0); + return; + } + + if (typeof document !== "undefined") { + this.index = Request.requestsCount++; + Request.requests[this.index] = this; + } + } + /** + * Called upon error. + * + * @api private + */ + + }, { + key: "onError", + value: function onError(err) { + this.emitReserved("error", err, this.xhr); + this.cleanup(true); + } + /** + * Cleans up house. + * + * @api private + */ + + }, { + key: "cleanup", + value: function cleanup(fromError) { + if ("undefined" === typeof this.xhr || null === this.xhr) { + return; + } + + this.xhr.onreadystatechange = empty; + + if (fromError) { + try { + this.xhr.abort(); + } catch (e) {} + } + + if (typeof document !== "undefined") { + delete Request.requests[this.index]; + } + + this.xhr = null; + } + /** + * Called upon load. + * + * @api private + */ + + }, { + key: "onLoad", + value: function onLoad() { + var data = this.xhr.responseText; + + if (data !== null) { + this.emitReserved("data", data); + this.emitReserved("success"); + this.cleanup(); + } + } + /** + * Aborts the request. + * + * @api public + */ + + }, { + key: "abort", + value: function abort() { + this.cleanup(); + } + }]); + + return Request; + }(Emitter); + Request.requestsCount = 0; + Request.requests = {}; + /** + * Aborts pending requests when unloading the window. This is needed to prevent + * memory leaks (e.g. when using IE) and to ensure that no spurious error is + * emitted. + */ + + if (typeof document !== "undefined") { + // @ts-ignore + if (typeof attachEvent === "function") { + // @ts-ignore + attachEvent("onunload", unloadHandler); + } else if (typeof addEventListener === "function") { + var terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload"; + addEventListener(terminationEvent, unloadHandler, false); + } + } + + function unloadHandler() { + for (var i in Request.requests) { + if (Request.requests.hasOwnProperty(i)) { + Request.requests[i].abort(); + } + } + } + + var nextTick = function () { + var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; + + if (isPromiseAvailable) { + return function (cb) { + return Promise.resolve().then(cb); + }; + } else { + return function (cb, setTimeoutFn) { + return setTimeoutFn(cb, 0); + }; + } + }(); + var WebSocket = globalThis.WebSocket || globalThis.MozWebSocket; + var usingBrowserWebSocket = true; + var defaultBinaryType = "arraybuffer"; + + var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative"; + var WS = /*#__PURE__*/function (_Transport) { + _inherits(WS, _Transport); + + var _super = _createSuper(WS); + + /** + * WebSocket transport constructor. + * + * @api {Object} connection options + * @api public + */ + function WS(opts) { + var _this; + + _classCallCheck(this, WS); + + _this = _super.call(this, opts); + _this.supportsBinary = !opts.forceBase64; + return _this; + } + /** + * Transport name. + * + * @api public + */ + + + _createClass(WS, [{ + key: "name", + get: function get() { + return "websocket"; + } + /** + * Opens socket. + * + * @api private + */ + + }, { + key: "doOpen", + value: function doOpen() { + if (!this.check()) { + // let probe timeout + return; + } + + var uri = this.uri(); + var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed + + var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); + + if (this.opts.extraHeaders) { + opts.headers = this.opts.extraHeaders; + } + + try { + this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts); + } catch (err) { + return this.emitReserved("error", err); + } + + this.ws.binaryType = this.socket.binaryType || defaultBinaryType; + this.addEventListeners(); + } + /** + * Adds event listeners to the socket + * + * @api private + */ + + }, { + key: "addEventListeners", + value: function addEventListeners() { + var _this2 = this; + + this.ws.onopen = function () { + if (_this2.opts.autoUnref) { + _this2.ws._socket.unref(); + } + + _this2.onOpen(); + }; + + this.ws.onclose = function (closeEvent) { + return _this2.onClose({ + description: "websocket connection closed", + context: closeEvent + }); + }; + + this.ws.onmessage = function (ev) { + return _this2.onData(ev.data); + }; + + this.ws.onerror = function (e) { + return _this2.onError("websocket error", e); + }; + } + /** + * Writes data to socket. + * + * @param {Array} array of packets. + * @api private + */ + + }, { + key: "write", + value: function write(packets) { + var _this3 = this; + + this.writable = false; // encodePacket efficient as it uses WS framing + // no need for encodePayload + + var _loop = function _loop(i) { + var packet = packets[i]; + var lastPacket = i === packets.length - 1; + encodePacket(packet, _this3.supportsBinary, function (data) { + // always create a new object (GH-437) + var opts = {}; + // have a chance of informing us about it yet, in that case send will + // throw an error + + + try { + if (usingBrowserWebSocket) { + // TypeError is thrown when passing the second argument on Safari + _this3.ws.send(data); + } + } catch (e) {} + + if (lastPacket) { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + nextTick(function () { + _this3.writable = true; + + _this3.emitReserved("drain"); + }, _this3.setTimeoutFn); + } + }); + }; + + for (var i = 0; i < packets.length; i++) { + _loop(i); + } + } + /** + * Closes socket. + * + * @api private + */ + + }, { + key: "doClose", + value: function doClose() { + if (typeof this.ws !== "undefined") { + this.ws.close(); + this.ws = null; + } + } + /** + * Generates uri for connection. + * + * @api private + */ + + }, { + key: "uri", + value: function uri() { + var query = this.query || {}; + var schema = this.opts.secure ? "wss" : "ws"; + var port = ""; // avoid port if default for schema + + if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) { + port = ":" + this.opts.port; + } // append timestamp to URI + + + if (this.opts.timestampRequests) { + query[this.opts.timestampParam] = yeast(); + } // communicate binary support capabilities + + + if (!this.supportsBinary) { + query.b64 = 1; + } + + var encodedQuery = encode(query); + var ipv6 = this.opts.hostname.indexOf(":") !== -1; + return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : ""); + } + /** + * Feature detection for WebSocket. + * + * @return {Boolean} whether this transport is available. + * @api public + */ + + }, { + key: "check", + value: function check() { + return !!WebSocket && !("__initialize" in WebSocket && this.name === WS.prototype.name); + } + }]); + + return WS; + }(Transport); + + var transports = { + websocket: WS, + polling: Polling + }; + + // imported from https://github.com/galkn/parseuri + + /** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ + var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor']; + function parse(str) { + var src = str, + b = str.indexOf('['), + e = str.indexOf(']'); + + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + + var m = re.exec(str || ''), + uri = {}, + i = 14; + + while (i--) { + uri[parts[i]] = m[i] || ''; + } + + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + + uri.pathNames = pathNames(uri, uri['path']); + uri.queryKey = queryKey(uri, uri['query']); + return uri; + } + + function pathNames(obj, path) { + var regx = /\/{2,9}/g, + names = path.replace(regx, "/").split("/"); + + if (path.substr(0, 1) == '/' || path.length === 0) { + names.splice(0, 1); + } + + if (path.substr(path.length - 1, 1) == '/') { + names.splice(names.length - 1, 1); + } + + return names; + } + + function queryKey(uri, query) { + var data = {}; + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { + if ($1) { + data[$1] = $2; + } + }); + return data; + } + + var Socket$1 = /*#__PURE__*/function (_Emitter) { + _inherits(Socket, _Emitter); + + var _super = _createSuper(Socket); + + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} opts - options + * @api public + */ + function Socket(uri) { + var _this; + + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, Socket); + + _this = _super.call(this); + + if (uri && "object" === _typeof(uri)) { + opts = uri; + uri = null; + } + + if (uri) { + uri = parse(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) opts.query = uri.query; + } else if (opts.host) { + opts.hostname = parse(opts.host).host; + } + + installTimerFunctions(_assertThisInitialized(_this), opts); + _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol; + + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = _this.secure ? "443" : "80"; + } + + _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost"); + _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80"); + _this.transports = opts.transports || ["polling", "websocket"]; + _this.readyState = ""; + _this.writeBuffer = []; + _this.prevBufferLen = 0; + _this.opts = _extends({ + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {}, + closeOnBeforeunload: true + }, opts); + _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/"; + + if (typeof _this.opts.query === "string") { + _this.opts.query = decode(_this.opts.query); + } // set on handshake + + + _this.id = null; + _this.upgrades = null; + _this.pingInterval = null; + _this.pingTimeout = null; // set on heartbeat + + _this.pingTimeoutTimer = null; + + if (typeof addEventListener === "function") { + if (_this.opts.closeOnBeforeunload) { + // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener + // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is + // closed/reloaded) + addEventListener("beforeunload", function () { + if (_this.transport) { + // silently close the transport + _this.transport.removeAllListeners(); + + _this.transport.close(); + } + }, false); + } + + if (_this.hostname !== "localhost") { + _this.offlineEventListener = function () { + _this.onClose("transport close", { + description: "network connection lost" + }); + }; + + addEventListener("offline", _this.offlineEventListener, false); + } + } + + _this.open(); + + return _this; + } + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + + + _createClass(Socket, [{ + key: "createTransport", + value: function createTransport(name) { + var query = _extends({}, this.opts.query); // append engine.io protocol identifier + + + query.EIO = protocol$1; // transport name + + query.transport = name; // session id if we already have one + + if (this.id) query.sid = this.id; + + var opts = _extends({}, this.opts.transportOptions[name], this.opts, { + query: query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + }); + + return new transports[name](opts); + } + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + + }, { + key: "open", + value: function open() { + var _this2 = this; + + var transport; + + if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) { + transport = "websocket"; + } else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + this.setTimeoutFn(function () { + _this2.emitReserved("error", "No transports available"); + }, 0); + return; + } else { + transport = this.transports[0]; + } + + this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false) + + try { + transport = this.createTransport(transport); + } catch (e) { + this.transports.shift(); + this.open(); + return; + } + + transport.open(); + this.setTransport(transport); + } + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + + }, { + key: "setTransport", + value: function setTransport(transport) { + var _this3 = this; + + if (this.transport) { + this.transport.removeAllListeners(); + } // set up transport + + + this.transport = transport; // set up transport listeners + + transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) { + return _this3.onClose("transport close", reason); + }); + } + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + + }, { + key: "probe", + value: function probe(name) { + var _this4 = this; + + var transport = this.createTransport(name); + var failed = false; + Socket.priorWebsocketSuccess = false; + + var onTransportOpen = function onTransportOpen() { + if (failed) return; + transport.send([{ + type: "ping", + data: "probe" + }]); + transport.once("packet", function (msg) { + if (failed) return; + + if ("pong" === msg.type && "probe" === msg.data) { + _this4.upgrading = true; + + _this4.emitReserved("upgrading", transport); + + if (!transport) return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + + _this4.transport.pause(function () { + if (failed) return; + if ("closed" === _this4.readyState) return; + cleanup(); + + _this4.setTransport(transport); + + transport.send([{ + type: "upgrade" + }]); + + _this4.emitReserved("upgrade", transport); + + transport = null; + _this4.upgrading = false; + + _this4.flush(); + }); + } else { + var err = new Error("probe error"); // @ts-ignore + + err.transport = transport.name; + + _this4.emitReserved("upgradeError", err); + } + }); + }; + + function freezeTransport() { + if (failed) return; // Any callback called by transport should be ignored since now + + failed = true; + cleanup(); + transport.close(); + transport = null; + } // Handle any error that happens while probing + + + var onerror = function onerror(err) { + var error = new Error("probe error: " + err); // @ts-ignore + + error.transport = transport.name; + freezeTransport(); + + _this4.emitReserved("upgradeError", error); + }; + + function onTransportClose() { + onerror("transport closed"); + } // When the socket is closed while we're probing + + + function onclose() { + onerror("socket closed"); + } // When the socket is upgraded while we're probing + + + function onupgrade(to) { + if (transport && to.name !== transport.name) { + freezeTransport(); + } + } // Remove all listeners on the transport and on self + + + var cleanup = function cleanup() { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + + _this4.off("close", onclose); + + _this4.off("upgrading", onupgrade); + }; + + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); + this.once("close", onclose); + this.once("upgrading", onupgrade); + transport.open(); + } + /** + * Called when connection is deemed open. + * + * @api private + */ + + }, { + key: "onOpen", + value: function onOpen() { + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emitReserved("open"); + this.flush(); // we check for `readyState` in case an `open` + // listener already closed the socket + + if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) { + var i = 0; + var l = this.upgrades.length; + + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } + } + /** + * Handles a packet. + * + * @api private + */ + + }, { + key: "onPacket", + value: function onPacket(packet) { + if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { + this.emitReserved("packet", packet); // Socket is live - any packet counts + + this.emitReserved("heartbeat"); + + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; + + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emitReserved("ping"); + this.emitReserved("pong"); + break; + + case "error": + var err = new Error("server error"); // @ts-ignore + + err.code = packet.data; + this.onError(err); + break; + + case "message": + this.emitReserved("data", packet.data); + this.emitReserved("message", packet.data); + break; + } + } + } + /** + * Called upon handshake completion. + * + * @param {Object} data - handshake obj + * @api private + */ + + }, { + key: "onHandshake", + value: function onHandshake(data) { + this.emitReserved("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.maxPayload = data.maxPayload; + this.onOpen(); // In case open handler closes socket + + if ("closed" === this.readyState) return; + this.resetPingTimeout(); + } + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + + }, { + key: "resetPingTimeout", + value: function resetPingTimeout() { + var _this5 = this; + + this.clearTimeoutFn(this.pingTimeoutTimer); + this.pingTimeoutTimer = this.setTimeoutFn(function () { + _this5.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } + } + /** + * Called on `drain` event + * + * @api private + */ + + }, { + key: "onDrain", + value: function onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + + this.prevBufferLen = 0; + + if (0 === this.writeBuffer.length) { + this.emitReserved("drain"); + } else { + this.flush(); + } + } + /** + * Flush write buffers. + * + * @api private + */ + + }, { + key: "flush", + value: function flush() { + if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { + var packets = this.getWritablePackets(); + this.transport.send(packets); // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + + this.prevBufferLen = packets.length; + this.emitReserved("flush"); + } + } + /** + * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP + * long-polling) + * + * @private + */ + + }, { + key: "getWritablePackets", + value: function getWritablePackets() { + var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1; + + if (!shouldCheckPayloadSize) { + return this.writeBuffer; + } + + var payloadSize = 1; // first packet type + + for (var i = 0; i < this.writeBuffer.length; i++) { + var data = this.writeBuffer[i].data; + + if (data) { + payloadSize += byteLength(data); + } + + if (i > 0 && payloadSize > this.maxPayload) { + return this.writeBuffer.slice(0, i); + } + + payloadSize += 2; // separator + packet type + } + + return this.writeBuffer; + } + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + + }, { + key: "write", + value: function write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + }, { + key: "send", + value: function send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + + }, { + key: "sendPacket", + value: function sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; + } + + if ("function" === typeof options) { + fn = options; + options = null; + } + + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } + + options = options || {}; + options.compress = false !== options.compress; + var packet = { + type: type, + data: data, + options: options + }; + this.emitReserved("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) this.once("flush", fn); + this.flush(); + } + /** + * Closes the connection. + * + * @api public + */ + + }, { + key: "close", + value: function close() { + var _this6 = this; + + var close = function close() { + _this6.onClose("forced close"); + + _this6.transport.close(); + }; + + var cleanupAndClose = function cleanupAndClose() { + _this6.off("upgrade", cleanupAndClose); + + _this6.off("upgradeError", cleanupAndClose); + + close(); + }; + + var waitForUpgrade = function waitForUpgrade() { + // wait for upgrade to finish since we can't send packets while pausing a transport + _this6.once("upgrade", cleanupAndClose); + + _this6.once("upgradeError", cleanupAndClose); + }; + + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; + + if (this.writeBuffer.length) { + this.once("drain", function () { + if (_this6.upgrading) { + waitForUpgrade(); + } else { + close(); + } + }); + } else if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + } + + return this; + } + /** + * Called upon transport error + * + * @api private + */ + + }, { + key: "onError", + value: function onError(err) { + Socket.priorWebsocketSuccess = false; + this.emitReserved("error", err); + this.onClose("transport error", err); + } + /** + * Called upon transport close. + * + * @api private + */ + + }, { + key: "onClose", + value: function onClose(reason, description) { + if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { + // clear timers + this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport + + this.transport.removeAllListeners("close"); // ensure transport won't stay open + + this.transport.close(); // ignore further transport communication + + this.transport.removeAllListeners(); + + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } // set ready state + + + this.readyState = "closed"; // clear session id + + this.id = null; // emit close event + + this.emitReserved("close", reason, description); // clean buffers after, so users can still + // grab the buffers on `close` event + + this.writeBuffer = []; + this.prevBufferLen = 0; + } + } + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + + }, { + key: "filterUpgrades", + value: function filterUpgrades(upgrades) { + var filteredUpgrades = []; + var i = 0; + var j = upgrades.length; + + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]); + } + + return filteredUpgrades; + } + }]); + + return Socket; + }(Emitter); + Socket$1.protocol = protocol$1; + + /** + * URL parser. + * + * @param uri - url + * @param path - the request path of the connection + * @param loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ + + function url(uri) { + var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + var loc = arguments.length > 2 ? arguments[2] : undefined; + var obj = uri; // default to window.location + + loc = loc || typeof location !== "undefined" && location; + if (null == uri) uri = loc.protocol + "//" + loc.host; // relative path support + + if (typeof uri === "string") { + if ("/" === uri.charAt(0)) { + if ("/" === uri.charAt(1)) { + uri = loc.protocol + uri; + } else { + uri = loc.host + uri; + } + } + + if (!/^(https?|wss?):\/\//.test(uri)) { + if ("undefined" !== typeof loc) { + uri = loc.protocol + "//" + uri; + } else { + uri = "https://" + uri; + } + } // parse + + + obj = parse(uri); + } // make sure we treat `localhost:80` and `localhost` equally + + + if (!obj.port) { + if (/^(http|ws)$/.test(obj.protocol)) { + obj.port = "80"; + } else if (/^(http|ws)s$/.test(obj.protocol)) { + obj.port = "443"; + } + } + + obj.path = obj.path || "/"; + var ipv6 = obj.host.indexOf(":") !== -1; + var host = ipv6 ? "[" + obj.host + "]" : obj.host; // define unique id + + obj.id = obj.protocol + "://" + host + ":" + obj.port + path; // define href + + obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port); + return obj; + } + + var withNativeArrayBuffer = typeof ArrayBuffer === "function"; + + var isView = function isView(obj) { + return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer; + }; + + var toString = Object.prototype.toString; + var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]"; + var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]"; + /** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ + + function isBinary(obj) { + return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File; + } + function hasBinary(obj, toJSON) { + if (!obj || _typeof(obj) !== "object") { + return false; + } + + if (Array.isArray(obj)) { + for (var i = 0, l = obj.length; i < l; i++) { + if (hasBinary(obj[i])) { + return true; + } + } + + return false; + } + + if (isBinary(obj)) { + return true; + } + + if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) { + return hasBinary(obj.toJSON(), true); + } + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + return true; + } + } + + return false; + } + + /** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ + + function deconstructPacket(packet) { + var buffers = []; + var packetData = packet.data; + var pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + + return { + packet: pack, + buffers: buffers + }; + } + + function _deconstructPacket(data, buffers) { + if (!data) return data; + + if (isBinary(data)) { + var placeholder = { + _placeholder: true, + num: buffers.length + }; + buffers.push(data); + return placeholder; + } else if (Array.isArray(data)) { + var newData = new Array(data.length); + + for (var i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + + return newData; + } else if (_typeof(data) === "object" && !(data instanceof Date)) { + var _newData = {}; + + for (var key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + _newData[key] = _deconstructPacket(data[key], buffers); + } + } + + return _newData; + } + + return data; + } + /** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ + + + function reconstructPacket(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + + return packet; + } + + function _reconstructPacket(data, buffers) { + if (!data) return data; + + if (data && data._placeholder) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } else if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } else if (_typeof(data) === "object") { + for (var key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + } + + return data; + } + + /** + * Protocol version. + * + * @public + */ + + var protocol = 5; + var PacketType; + + (function (PacketType) { + PacketType[PacketType["CONNECT"] = 0] = "CONNECT"; + PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT"; + PacketType[PacketType["EVENT"] = 2] = "EVENT"; + PacketType[PacketType["ACK"] = 3] = "ACK"; + PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR"; + PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT"; + PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK"; + })(PacketType || (PacketType = {})); + /** + * A socket.io Encoder instance + */ + + + var Encoder = /*#__PURE__*/function () { + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + function Encoder(replacer) { + _classCallCheck(this, Encoder); + + this.replacer = replacer; + } + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + + + _createClass(Encoder, [{ + key: "encode", + value: function encode(obj) { + if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) { + if (hasBinary(obj)) { + obj.type = obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK; + return this.encodeAsBinary(obj); + } + } + + return [this.encodeAsString(obj)]; + } + /** + * Encode packet as string. + */ + + }, { + key: "encodeAsString", + value: function encodeAsString(obj) { + // first is type + var str = "" + obj.type; // attachments if we have them + + if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) { + str += obj.attachments + "-"; + } // if we have a namespace other than `/` + // we append it followed by a comma `,` + + + if (obj.nsp && "/" !== obj.nsp) { + str += obj.nsp + ","; + } // immediately followed by the id + + + if (null != obj.id) { + str += obj.id; + } // json data + + + if (null != obj.data) { + str += JSON.stringify(obj.data, this.replacer); + } + + return str; + } + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + + }, { + key: "encodeAsBinary", + value: function encodeAsBinary(obj) { + var deconstruction = deconstructPacket(obj); + var pack = this.encodeAsString(deconstruction.packet); + var buffers = deconstruction.buffers; + buffers.unshift(pack); // add packet info to beginning of data list + + return buffers; // write all the buffers + } + }]); + + return Encoder; + }(); + /** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ + + var Decoder = /*#__PURE__*/function (_Emitter) { + _inherits(Decoder, _Emitter); + + var _super = _createSuper(Decoder); + + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + function Decoder(reviver) { + var _this; + + _classCallCheck(this, Decoder); + + _this = _super.call(this); + _this.reviver = reviver; + return _this; + } + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + + + _createClass(Decoder, [{ + key: "add", + value: function add(obj) { + var packet; + + if (typeof obj === "string") { + packet = this.decodeString(obj); + + if (packet.type === PacketType.BINARY_EVENT || packet.type === PacketType.BINARY_ACK) { + // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow + + if (packet.attachments === 0) { + _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); + } + } else { + // non-binary full packet + _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); + } + } else if (isBinary(obj) || obj.base64) { + // raw binary data + if (!this.reconstructor) { + throw new Error("got binary data when not reconstructing a packet"); + } else { + packet = this.reconstructor.takeBinaryData(obj); + + if (packet) { + // received final buffer + this.reconstructor = null; + + _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); + } + } + } else { + throw new Error("Unknown type: " + obj); + } + } + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + + }, { + key: "decodeString", + value: function decodeString(str) { + var i = 0; // look up type + + var p = { + type: Number(str.charAt(0)) + }; + + if (PacketType[p.type] === undefined) { + throw new Error("unknown packet type " + p.type); + } // look up attachments if type binary + + + if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) { + var start = i + 1; + + while (str.charAt(++i) !== "-" && i != str.length) {} + + var buf = str.substring(start, i); + + if (buf != Number(buf) || str.charAt(i) !== "-") { + throw new Error("Illegal attachments"); + } + + p.attachments = Number(buf); + } // look up namespace (if any) + + + if ("/" === str.charAt(i + 1)) { + var _start = i + 1; + + while (++i) { + var c = str.charAt(i); + if ("," === c) break; + if (i === str.length) break; + } + + p.nsp = str.substring(_start, i); + } else { + p.nsp = "/"; + } // look up id + + + var next = str.charAt(i + 1); + + if ("" !== next && Number(next) == next) { + var _start2 = i + 1; + + while (++i) { + var _c = str.charAt(i); + + if (null == _c || Number(_c) != _c) { + --i; + break; + } + + if (i === str.length) break; + } + + p.id = Number(str.substring(_start2, i + 1)); + } // look up json data + + + if (str.charAt(++i)) { + var payload = this.tryParse(str.substr(i)); + + if (Decoder.isPayloadValid(p.type, payload)) { + p.data = payload; + } else { + throw new Error("invalid payload"); + } + } + + return p; + } + }, { + key: "tryParse", + value: function tryParse(str) { + try { + return JSON.parse(str, this.reviver); + } catch (e) { + return false; + } + } + }, { + key: "destroy", + value: + /** + * Deallocates a parser's resources + */ + function destroy() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } + } + }], [{ + key: "isPayloadValid", + value: function isPayloadValid(type, payload) { + switch (type) { + case PacketType.CONNECT: + return _typeof(payload) === "object"; + + case PacketType.DISCONNECT: + return payload === undefined; + + case PacketType.CONNECT_ERROR: + return typeof payload === "string" || _typeof(payload) === "object"; + + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + return Array.isArray(payload) && payload.length > 0; + + case PacketType.ACK: + case PacketType.BINARY_ACK: + return Array.isArray(payload); + } + } + }]); + + return Decoder; + }(Emitter); + /** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + */ + + var BinaryReconstructor = /*#__PURE__*/function () { + function BinaryReconstructor(packet) { + _classCallCheck(this, BinaryReconstructor); + + this.packet = packet; + this.buffers = []; + this.reconPack = packet; + } + /** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + */ + + + _createClass(BinaryReconstructor, [{ + key: "takeBinaryData", + value: function takeBinaryData(binData) { + this.buffers.push(binData); + + if (this.buffers.length === this.reconPack.attachments) { + // done with buffer list + var packet = reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + + return null; + } + /** + * Cleans up binary packet reconstruction variables. + */ + + }, { + key: "finishedReconstruction", + value: function finishedReconstruction() { + this.reconPack = null; + this.buffers = []; + } + }]); + + return BinaryReconstructor; + }(); + + var parser = /*#__PURE__*/Object.freeze({ + __proto__: null, + protocol: protocol, + get PacketType () { return PacketType; }, + Encoder: Encoder, + Decoder: Decoder + }); + + function on(obj, ev, fn) { + obj.on(ev, fn); + return function subDestroy() { + obj.off(ev, fn); + }; + } + + /** + * Internal events. + * These events can't be emitted by the user. + */ + + var RESERVED_EVENTS = Object.freeze({ + connect: 1, + connect_error: 1, + disconnect: 1, + disconnecting: 1, + // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener + newListener: 1, + removeListener: 1 + }); + var Socket = /*#__PURE__*/function (_Emitter) { + _inherits(Socket, _Emitter); + + var _super = _createSuper(Socket); + + /** + * `Socket` constructor. + * + * @public + */ + function Socket(io, nsp, opts) { + var _this; + + _classCallCheck(this, Socket); + + _this = _super.call(this); + _this.connected = false; + _this.receiveBuffer = []; + _this.sendBuffer = []; + _this.ids = 0; + _this.acks = {}; + _this.flags = {}; + _this.io = io; + _this.nsp = nsp; + + if (opts && opts.auth) { + _this.auth = opts.auth; + } + + if (_this.io._autoConnect) _this.open(); + return _this; + } + /** + * Whether the socket is currently disconnected + */ + + + _createClass(Socket, [{ + key: "disconnected", + get: function get() { + return !this.connected; + } + /** + * Subscribe to open, close and packet events + * + * @private + */ + + }, { + key: "subEvents", + value: function subEvents() { + if (this.subs) return; + var io = this.io; + this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))]; + } + /** + * Whether the Socket will try to reconnect when its Manager connects or reconnects + */ + + }, { + key: "active", + get: function get() { + return !!this.subs; + } + /** + * "Opens" the socket. + * + * @public + */ + + }, { + key: "connect", + value: function connect() { + if (this.connected) return this; + this.subEvents(); + if (!this.io["_reconnecting"]) this.io.open(); // ensure open + + if ("open" === this.io._readyState) this.onopen(); + return this; + } + /** + * Alias for connect() + */ + + }, { + key: "open", + value: function open() { + return this.connect(); + } + /** + * Sends a `message` event. + * + * @return self + * @public + */ + + }, { + key: "send", + value: function send() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + args.unshift("message"); + this.emit.apply(this, args); + return this; + } + /** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @return self + * @public + */ + + }, { + key: "emit", + value: function emit(ev) { + if (RESERVED_EVENTS.hasOwnProperty(ev)) { + throw new Error('"' + ev + '" is a reserved event name'); + } + + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + args.unshift(ev); + var packet = { + type: PacketType.EVENT, + data: args + }; + packet.options = {}; + packet.options.compress = this.flags.compress !== false; // event ack callback + + if ("function" === typeof args[args.length - 1]) { + var id = this.ids++; + var ack = args.pop(); + + this._registerAckCallback(id, ack); + + packet.id = id; + } + + var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable; + var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected); + + if (discardPacket) ; else if (this.connected) { + this.notifyOutgoingListeners(packet); + this.packet(packet); + } else { + this.sendBuffer.push(packet); + } + + this.flags = {}; + return this; + } + /** + * @private + */ + + }, { + key: "_registerAckCallback", + value: function _registerAckCallback(id, ack) { + var _this2 = this; + + var timeout = this.flags.timeout; + + if (timeout === undefined) { + this.acks[id] = ack; + return; + } // @ts-ignore + + + var timer = this.io.setTimeoutFn(function () { + delete _this2.acks[id]; + + for (var i = 0; i < _this2.sendBuffer.length; i++) { + if (_this2.sendBuffer[i].id === id) { + _this2.sendBuffer.splice(i, 1); + } + } + + ack.call(_this2, new Error("operation has timed out")); + }, timeout); + + this.acks[id] = function () { + // @ts-ignore + _this2.io.clearTimeoutFn(timer); + + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + ack.apply(_this2, [null].concat(args)); + }; + } + /** + * Sends a packet. + * + * @param packet + * @private + */ + + }, { + key: "packet", + value: function packet(_packet) { + _packet.nsp = this.nsp; + + this.io._packet(_packet); + } + /** + * Called upon engine `open`. + * + * @private + */ + + }, { + key: "onopen", + value: function onopen() { + var _this3 = this; + + if (typeof this.auth == "function") { + this.auth(function (data) { + _this3.packet({ + type: PacketType.CONNECT, + data: data + }); + }); + } else { + this.packet({ + type: PacketType.CONNECT, + data: this.auth + }); + } + } + /** + * Called upon engine or manager `error`. + * + * @param err + * @private + */ + + }, { + key: "onerror", + value: function onerror(err) { + if (!this.connected) { + this.emitReserved("connect_error", err); + } + } + /** + * Called upon engine `close`. + * + * @param reason + * @param description + * @private + */ + + }, { + key: "onclose", + value: function onclose(reason, description) { + this.connected = false; + delete this.id; + this.emitReserved("disconnect", reason, description); + } + /** + * Called with socket packet. + * + * @param packet + * @private + */ + + }, { + key: "onpacket", + value: function onpacket(packet) { + var sameNamespace = packet.nsp === this.nsp; + if (!sameNamespace) return; + + switch (packet.type) { + case PacketType.CONNECT: + if (packet.data && packet.data.sid) { + var id = packet.data.sid; + this.onconnect(id); + } else { + this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)")); + } + + break; + + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + this.onevent(packet); + break; + + case PacketType.ACK: + case PacketType.BINARY_ACK: + this.onack(packet); + break; + + case PacketType.DISCONNECT: + this.ondisconnect(); + break; + + case PacketType.CONNECT_ERROR: + this.destroy(); + var err = new Error(packet.data.message); // @ts-ignore + + err.data = packet.data.data; + this.emitReserved("connect_error", err); + break; + } + } + /** + * Called upon a server event. + * + * @param packet + * @private + */ + + }, { + key: "onevent", + value: function onevent(packet) { + var args = packet.data || []; + + if (null != packet.id) { + args.push(this.ack(packet.id)); + } + + if (this.connected) { + this.emitEvent(args); + } else { + this.receiveBuffer.push(Object.freeze(args)); + } + } + }, { + key: "emitEvent", + value: function emitEvent(args) { + if (this._anyListeners && this._anyListeners.length) { + var listeners = this._anyListeners.slice(); + + var _iterator = _createForOfIteratorHelper(listeners), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var listener = _step.value; + listener.apply(this, args); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + + _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args); + } + /** + * Produces an ack callback to emit with an event. + * + * @private + */ + + }, { + key: "ack", + value: function ack(id) { + var self = this; + var sent = false; + return function () { + // prevent double callbacks + if (sent) return; + sent = true; + + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + self.packet({ + type: PacketType.ACK, + id: id, + data: args + }); + }; + } + /** + * Called upon a server acknowlegement. + * + * @param packet + * @private + */ + + }, { + key: "onack", + value: function onack(packet) { + var ack = this.acks[packet.id]; + + if ("function" === typeof ack) { + ack.apply(this, packet.data); + delete this.acks[packet.id]; + } + } + /** + * Called upon server connect. + * + * @private + */ + + }, { + key: "onconnect", + value: function onconnect(id) { + this.id = id; + this.connected = true; + this.emitBuffered(); + this.emitReserved("connect"); + } + /** + * Emit buffered events (received and emitted). + * + * @private + */ + + }, { + key: "emitBuffered", + value: function emitBuffered() { + var _this4 = this; + + this.receiveBuffer.forEach(function (args) { + return _this4.emitEvent(args); + }); + this.receiveBuffer = []; + this.sendBuffer.forEach(function (packet) { + _this4.notifyOutgoingListeners(packet); + + _this4.packet(packet); + }); + this.sendBuffer = []; + } + /** + * Called upon server disconnect. + * + * @private + */ + + }, { + key: "ondisconnect", + value: function ondisconnect() { + this.destroy(); + this.onclose("io server disconnect"); + } + /** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @private + */ + + }, { + key: "destroy", + value: function destroy() { + if (this.subs) { + // clean subscriptions to avoid reconnections + this.subs.forEach(function (subDestroy) { + return subDestroy(); + }); + this.subs = undefined; + } + + this.io["_destroy"](this); + } + /** + * Disconnects the socket manually. + * + * @return self + * @public + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.connected) { + this.packet({ + type: PacketType.DISCONNECT + }); + } // remove socket from pool + + + this.destroy(); + + if (this.connected) { + // fire events + this.onclose("io client disconnect"); + } + + return this; + } + /** + * Alias for disconnect() + * + * @return self + * @public + */ + + }, { + key: "close", + value: function close() { + return this.disconnect(); + } + /** + * Sets the compress flag. + * + * @param compress - if `true`, compresses the sending data + * @return self + * @public + */ + + }, { + key: "compress", + value: function compress(_compress) { + this.flags.compress = _compress; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not + * ready to send messages. + * + * @returns self + * @public + */ + + }, { + key: "volatile", + get: function get() { + this.flags["volatile"] = true; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the server: + * + * ``` + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the server did not acknowledge the event in the given delay + * } + * }); + * ``` + * + * @returns self + * @public + */ + + }, { + key: "timeout", + value: function timeout(_timeout) { + this.flags.timeout = _timeout; + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * @public + */ + + }, { + key: "onAny", + value: function onAny(listener) { + this._anyListeners = this._anyListeners || []; + + this._anyListeners.push(listener); + + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * @public + */ + + }, { + key: "prependAny", + value: function prependAny(listener) { + this._anyListeners = this._anyListeners || []; + + this._anyListeners.unshift(listener); + + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * @public + */ + + }, { + key: "offAny", + value: function offAny(listener) { + if (!this._anyListeners) { + return this; + } + + if (listener) { + var listeners = this._anyListeners; + + for (var i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } else { + this._anyListeners = []; + } + + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + + }, { + key: "listenersAny", + value: function listenersAny() { + return this._anyListeners || []; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. + * + * @param listener + * + *

+       *
+       * socket.onAnyOutgoing((event, ...args) => {
+       *   console.log(event);
+       * });
+       *
+       * 
+ * + * @public + */ + + }, { + key: "onAnyOutgoing", + value: function onAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + + this._anyOutgoingListeners.push(listener); + + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @param listener + * + *

+       *
+       * socket.prependAnyOutgoing((event, ...args) => {
+       *   console.log(event);
+       * });
+       *
+       * 
+ * + * @public + */ + + }, { + key: "prependAnyOutgoing", + value: function prependAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + + this._anyOutgoingListeners.unshift(listener); + + return this; + } + /** + * Removes the listener that will be fired when any event is emitted. + * + * @param listener + * + *

+       *
+       * const handler = (event, ...args) => {
+       *   console.log(event);
+       * }
+       *
+       * socket.onAnyOutgoing(handler);
+       *
+       * // then later
+       * socket.offAnyOutgoing(handler);
+       *
+       * 
+ * + * @public + */ + + }, { + key: "offAnyOutgoing", + value: function offAnyOutgoing(listener) { + if (!this._anyOutgoingListeners) { + return this; + } + + if (listener) { + var listeners = this._anyOutgoingListeners; + + for (var i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } else { + this._anyOutgoingListeners = []; + } + + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + * + * @public + */ + + }, { + key: "listenersAnyOutgoing", + value: function listenersAnyOutgoing() { + return this._anyOutgoingListeners || []; + } + /** + * Notify the listeners for each packet sent + * + * @param packet + * + * @private + */ + + }, { + key: "notifyOutgoingListeners", + value: function notifyOutgoingListeners(packet) { + if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { + var listeners = this._anyOutgoingListeners.slice(); + + var _iterator2 = _createForOfIteratorHelper(listeners), + _step2; + + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var listener = _step2.value; + listener.apply(this, packet.data); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + } + } + }]); + + return Socket; + }(Emitter); + + /** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ + function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; + } + /** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ + + Backoff.prototype.duration = function () { + var ms = this.ms * Math.pow(this.factor, this.attempts++); + + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; + } + + return Math.min(ms, this.max) | 0; + }; + /** + * Reset the number of attempts. + * + * @api public + */ + + + Backoff.prototype.reset = function () { + this.attempts = 0; + }; + /** + * Set the minimum duration + * + * @api public + */ + + + Backoff.prototype.setMin = function (min) { + this.ms = min; + }; + /** + * Set the maximum duration + * + * @api public + */ + + + Backoff.prototype.setMax = function (max) { + this.max = max; + }; + /** + * Set the jitter + * + * @api public + */ + + + Backoff.prototype.setJitter = function (jitter) { + this.jitter = jitter; + }; + + var Manager = /*#__PURE__*/function (_Emitter) { + _inherits(Manager, _Emitter); + + var _super = _createSuper(Manager); + + function Manager(uri, opts) { + var _this; + + _classCallCheck(this, Manager); + + var _a; + + _this = _super.call(this); + _this.nsps = {}; + _this.subs = []; + + if (uri && "object" === _typeof(uri)) { + opts = uri; + uri = undefined; + } + + opts = opts || {}; + opts.path = opts.path || "/socket.io"; + _this.opts = opts; + installTimerFunctions(_assertThisInitialized(_this), opts); + + _this.reconnection(opts.reconnection !== false); + + _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); + + _this.reconnectionDelay(opts.reconnectionDelay || 1000); + + _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); + + _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5); + + _this.backoff = new Backoff({ + min: _this.reconnectionDelay(), + max: _this.reconnectionDelayMax(), + jitter: _this.randomizationFactor() + }); + + _this.timeout(null == opts.timeout ? 20000 : opts.timeout); + + _this._readyState = "closed"; + _this.uri = uri; + + var _parser = opts.parser || parser; + + _this.encoder = new _parser.Encoder(); + _this.decoder = new _parser.Decoder(); + _this._autoConnect = opts.autoConnect !== false; + if (_this._autoConnect) _this.open(); + return _this; + } + + _createClass(Manager, [{ + key: "reconnection", + value: function reconnection(v) { + if (!arguments.length) return this._reconnection; + this._reconnection = !!v; + return this; + } + }, { + key: "reconnectionAttempts", + value: function reconnectionAttempts(v) { + if (v === undefined) return this._reconnectionAttempts; + this._reconnectionAttempts = v; + return this; + } + }, { + key: "reconnectionDelay", + value: function reconnectionDelay(v) { + var _a; + + if (v === undefined) return this._reconnectionDelay; + this._reconnectionDelay = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); + return this; + } + }, { + key: "randomizationFactor", + value: function randomizationFactor(v) { + var _a; + + if (v === undefined) return this._randomizationFactor; + this._randomizationFactor = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); + return this; + } + }, { + key: "reconnectionDelayMax", + value: function reconnectionDelayMax(v) { + var _a; + + if (v === undefined) return this._reconnectionDelayMax; + this._reconnectionDelayMax = v; + (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); + return this; + } + }, { + key: "timeout", + value: function timeout(v) { + if (!arguments.length) return this._timeout; + this._timeout = v; + return this; + } + /** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @private + */ + + }, { + key: "maybeReconnectOnOpen", + value: function maybeReconnectOnOpen() { + // Only try to reconnect if it's the first time we're connecting + if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) { + // keeps reconnection from firing twice for the same reconnection loop + this.reconnect(); + } + } + /** + * Sets the current transport `socket`. + * + * @param {Function} fn - optional, callback + * @return self + * @public + */ + + }, { + key: "open", + value: function open(fn) { + var _this2 = this; + + if (~this._readyState.indexOf("open")) return this; + this.engine = new Socket$1(this.uri, this.opts); + var socket = this.engine; + var self = this; + this._readyState = "opening"; + this.skipReconnect = false; // emit `open` + + var openSubDestroy = on(socket, "open", function () { + self.onopen(); + fn && fn(); + }); // emit `error` + + var errorSub = on(socket, "error", function (err) { + self.cleanup(); + self._readyState = "closed"; + + _this2.emitReserved("error", err); + + if (fn) { + fn(err); + } else { + // Only do this if there is no fn to handle the error + self.maybeReconnectOnOpen(); + } + }); + + if (false !== this._timeout) { + var timeout = this._timeout; + + if (timeout === 0) { + openSubDestroy(); // prevents a race condition with the 'open' event + } // set timer + + + var timer = this.setTimeoutFn(function () { + openSubDestroy(); + socket.close(); // @ts-ignore + + socket.emit("error", new Error("timeout")); + }, timeout); + + if (this.opts.autoUnref) { + timer.unref(); + } + + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + + this.subs.push(openSubDestroy); + this.subs.push(errorSub); + return this; + } + /** + * Alias for open() + * + * @return self + * @public + */ + + }, { + key: "connect", + value: function connect(fn) { + return this.open(fn); + } + /** + * Called upon transport open. + * + * @private + */ + + }, { + key: "onopen", + value: function onopen() { + // clear old subs + this.cleanup(); // mark as open + + this._readyState = "open"; + this.emitReserved("open"); // add new subs + + var socket = this.engine; + this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this))); + } + /** + * Called upon a ping. + * + * @private + */ + + }, { + key: "onping", + value: function onping() { + this.emitReserved("ping"); + } + /** + * Called with data. + * + * @private + */ + + }, { + key: "ondata", + value: function ondata(data) { + this.decoder.add(data); + } + /** + * Called when parser fully decodes a packet. + * + * @private + */ + + }, { + key: "ondecoded", + value: function ondecoded(packet) { + this.emitReserved("packet", packet); + } + /** + * Called upon socket error. + * + * @private + */ + + }, { + key: "onerror", + value: function onerror(err) { + this.emitReserved("error", err); + } + /** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @public + */ + + }, { + key: "socket", + value: function socket(nsp, opts) { + var socket = this.nsps[nsp]; + + if (!socket) { + socket = new Socket(this, nsp, opts); + this.nsps[nsp] = socket; + } + + return socket; + } + /** + * Called upon a socket close. + * + * @param socket + * @private + */ + + }, { + key: "_destroy", + value: function _destroy(socket) { + var nsps = Object.keys(this.nsps); + + for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) { + var nsp = _nsps[_i]; + var _socket = this.nsps[nsp]; + + if (_socket.active) { + return; + } + } + + this._close(); + } + /** + * Writes a packet. + * + * @param packet + * @private + */ + + }, { + key: "_packet", + value: function _packet(packet) { + var encodedPackets = this.encoder.encode(packet); + + for (var i = 0; i < encodedPackets.length; i++) { + this.engine.write(encodedPackets[i], packet.options); + } + } + /** + * Clean up transport subscriptions and packet buffer. + * + * @private + */ + + }, { + key: "cleanup", + value: function cleanup() { + this.subs.forEach(function (subDestroy) { + return subDestroy(); + }); + this.subs.length = 0; + this.decoder.destroy(); + } + /** + * Close the current socket. + * + * @private + */ + + }, { + key: "_close", + value: function _close() { + this.skipReconnect = true; + this._reconnecting = false; + this.onclose("forced close"); + if (this.engine) this.engine.close(); + } + /** + * Alias for close() + * + * @private + */ + + }, { + key: "disconnect", + value: function disconnect() { + return this._close(); + } + /** + * Called upon engine close. + * + * @private + */ + + }, { + key: "onclose", + value: function onclose(reason, description) { + this.cleanup(); + this.backoff.reset(); + this._readyState = "closed"; + this.emitReserved("close", reason, description); + + if (this._reconnection && !this.skipReconnect) { + this.reconnect(); + } + } + /** + * Attempt a reconnection. + * + * @private + */ + + }, { + key: "reconnect", + value: function reconnect() { + var _this3 = this; + + if (this._reconnecting || this.skipReconnect) return this; + var self = this; + + if (this.backoff.attempts >= this._reconnectionAttempts) { + this.backoff.reset(); + this.emitReserved("reconnect_failed"); + this._reconnecting = false; + } else { + var delay = this.backoff.duration(); + this._reconnecting = true; + var timer = this.setTimeoutFn(function () { + if (self.skipReconnect) return; + + _this3.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events + + + if (self.skipReconnect) return; + self.open(function (err) { + if (err) { + self._reconnecting = false; + self.reconnect(); + + _this3.emitReserved("reconnect_error", err); + } else { + self.onreconnect(); + } + }); + }, delay); + + if (this.opts.autoUnref) { + timer.unref(); + } + + this.subs.push(function subDestroy() { + clearTimeout(timer); + }); + } + } + /** + * Called upon successful reconnect. + * + * @private + */ + + }, { + key: "onreconnect", + value: function onreconnect() { + var attempt = this.backoff.attempts; + this._reconnecting = false; + this.backoff.reset(); + this.emitReserved("reconnect", attempt); + } + }]); + + return Manager; + }(Emitter); + + /** + * Managers cache. + */ + + var cache = {}; + + function lookup(uri, opts) { + if (_typeof(uri) === "object") { + opts = uri; + uri = undefined; + } + + opts = opts || {}; + var parsed = url(uri, opts.path || "/socket.io"); + var source = parsed.source; + var id = parsed.id; + var path = parsed.path; + var sameNamespace = cache[id] && path in cache[id]["nsps"]; + var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace; + var io; + + if (newConnection) { + io = new Manager(source, opts); + } else { + if (!cache[id]) { + cache[id] = new Manager(source, opts); + } + + io = cache[id]; + } + + if (parsed.query && !opts.query) { + opts.query = parsed.queryKey; + } + + return io.socket(parsed.path, opts); + } // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a + // namespace (e.g. `io.connect(...)`), for backward compatibility + + + _extends(lookup, { + Manager: Manager, + Socket: Socket, + io: lookup, + connect: lookup + }); + + return lookup; + +})); +//# sourceMappingURL=socket.io.js.map diff --git a/node_modules/socket.io-client/dist/socket.io.js.map b/node_modules/socket.io-client/dist/socket.io.js.map new file mode 100644 index 0000000..0def727 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socket.io.js","sources":["../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/commons.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/encodePacket.browser.js","../node_modules/@socket.io/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/decodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/index.js","../node_modules/@socket.io/component-emitter/index.mjs","../node_modules/engine.io-client/build/esm/globalThis.browser.js","../node_modules/engine.io-client/build/esm/util.js","../node_modules/engine.io-client/build/esm/transport.js","../node_modules/engine.io-client/build/esm/contrib/yeast.js","../node_modules/engine.io-client/build/esm/contrib/parseqs.js","../node_modules/engine.io-client/build/esm/contrib/has-cors.js","../node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js","../node_modules/engine.io-client/build/esm/transports/polling.js","../node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js","../node_modules/engine.io-client/build/esm/transports/websocket.js","../node_modules/engine.io-client/build/esm/transports/index.js","../node_modules/engine.io-client/build/esm/contrib/parseuri.js","../node_modules/engine.io-client/build/esm/socket.js","../build/esm/url.js","../node_modules/socket.io-parser/build/esm/is-binary.js","../node_modules/socket.io-parser/build/esm/binary.js","../node_modules/socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export default (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import globalThis from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport globalThis from \"../globalThis.js\";\nexport default function (opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport XMLHttpRequest from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport globalThis from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import globalThis from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return (!!WebSocket &&\n !(\"__initialize\" in WebSocket && this.name === WS.prototype.name));\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n","const withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n (typeof File !== \"undefined\" &&\n toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nexport function isBinary(obj) {\n return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n (withNativeBlob && obj instanceof Blob) ||\n (withNativeFile && obj instanceof File));\n}\nexport function hasBinary(obj, toJSON) {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n if (Array.isArray(obj)) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (hasBinary(obj[i])) {\n return true;\n }\n }\n return false;\n }\n if (isBinary(obj)) {\n return true;\n }\n if (obj.toJSON &&\n typeof obj.toJSON === \"function\" &&\n arguments.length === 1) {\n return hasBinary(obj.toJSON(), true);\n }\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n return true;\n }\n }\n return false;\n}\n","import { isBinary } from \"./is-binary.js\";\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nexport function deconstructPacket(packet) {\n const buffers = [];\n const packetData = packet.data;\n const pack = packet;\n pack.data = _deconstructPacket(packetData, buffers);\n pack.attachments = buffers.length; // number of binary 'attachments'\n return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (isBinary(data)) {\n const placeholder = { _placeholder: true, num: buffers.length };\n buffers.push(data);\n return placeholder;\n }\n else if (Array.isArray(data)) {\n const newData = new Array(data.length);\n for (let i = 0; i < data.length; i++) {\n newData[i] = _deconstructPacket(data[i], buffers);\n }\n return newData;\n }\n else if (typeof data === \"object\" && !(data instanceof Date)) {\n const newData = {};\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n newData[key] = _deconstructPacket(data[key], buffers);\n }\n }\n return newData;\n }\n return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nexport function reconstructPacket(packet, buffers) {\n packet.data = _reconstructPacket(packet.data, buffers);\n packet.attachments = undefined; // no longer useful\n return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (data && data._placeholder) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n }\n else if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n }\n else if (typeof data === \"object\") {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n }\n return data;\n}\n","import { Emitter } from \"@socket.io/component-emitter\";\nimport { deconstructPacket, reconstructPacket } from \"./binary.js\";\nimport { isBinary, hasBinary } from \"./is-binary.js\";\n/**\n * Protocol version.\n *\n * @public\n */\nexport const protocol = 5;\nexport var PacketType;\n(function (PacketType) {\n PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nexport class Encoder {\n /**\n * Encoder constructor\n *\n * @param {function} replacer - custom replacer to pass down to JSON.parse\n */\n constructor(replacer) {\n this.replacer = replacer;\n }\n /**\n * Encode a packet as a single string if non-binary, or as a\n * buffer sequence, depending on packet type.\n *\n * @param {Object} obj - packet object\n */\n encode(obj) {\n if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n if (hasBinary(obj)) {\n obj.type =\n obj.type === PacketType.EVENT\n ? PacketType.BINARY_EVENT\n : PacketType.BINARY_ACK;\n return this.encodeAsBinary(obj);\n }\n }\n return [this.encodeAsString(obj)];\n }\n /**\n * Encode packet as string.\n */\n encodeAsString(obj) {\n // first is type\n let str = \"\" + obj.type;\n // attachments if we have them\n if (obj.type === PacketType.BINARY_EVENT ||\n obj.type === PacketType.BINARY_ACK) {\n str += obj.attachments + \"-\";\n }\n // if we have a namespace other than `/`\n // we append it followed by a comma `,`\n if (obj.nsp && \"/\" !== obj.nsp) {\n str += obj.nsp + \",\";\n }\n // immediately followed by the id\n if (null != obj.id) {\n str += obj.id;\n }\n // json data\n if (null != obj.data) {\n str += JSON.stringify(obj.data, this.replacer);\n }\n return str;\n }\n /**\n * Encode packet as 'buffer sequence' by removing blobs, and\n * deconstructing packet into object with placeholders and\n * a list of buffers.\n */\n encodeAsBinary(obj) {\n const deconstruction = deconstructPacket(obj);\n const pack = this.encodeAsString(deconstruction.packet);\n const buffers = deconstruction.buffers;\n buffers.unshift(pack); // add packet info to beginning of data list\n return buffers; // write all the buffers\n }\n}\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nexport class Decoder extends Emitter {\n /**\n * Decoder constructor\n *\n * @param {function} reviver - custom reviver to pass down to JSON.stringify\n */\n constructor(reviver) {\n super();\n this.reviver = reviver;\n }\n /**\n * Decodes an encoded packet string into packet JSON.\n *\n * @param {String} obj - encoded packet\n */\n add(obj) {\n let packet;\n if (typeof obj === \"string\") {\n packet = this.decodeString(obj);\n if (packet.type === PacketType.BINARY_EVENT ||\n packet.type === PacketType.BINARY_ACK) {\n // binary packet's json\n this.reconstructor = new BinaryReconstructor(packet);\n // no attachments, labeled binary but no binary data to follow\n if (packet.attachments === 0) {\n super.emitReserved(\"decoded\", packet);\n }\n }\n else {\n // non-binary full packet\n super.emitReserved(\"decoded\", packet);\n }\n }\n else if (isBinary(obj) || obj.base64) {\n // raw binary data\n if (!this.reconstructor) {\n throw new Error(\"got binary data when not reconstructing a packet\");\n }\n else {\n packet = this.reconstructor.takeBinaryData(obj);\n if (packet) {\n // received final buffer\n this.reconstructor = null;\n super.emitReserved(\"decoded\", packet);\n }\n }\n }\n else {\n throw new Error(\"Unknown type: \" + obj);\n }\n }\n /**\n * Decode a packet String (JSON data)\n *\n * @param {String} str\n * @return {Object} packet\n */\n decodeString(str) {\n let i = 0;\n // look up type\n const p = {\n type: Number(str.charAt(0)),\n };\n if (PacketType[p.type] === undefined) {\n throw new Error(\"unknown packet type \" + p.type);\n }\n // look up attachments if type binary\n if (p.type === PacketType.BINARY_EVENT ||\n p.type === PacketType.BINARY_ACK) {\n const start = i + 1;\n while (str.charAt(++i) !== \"-\" && i != str.length) { }\n const buf = str.substring(start, i);\n if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n throw new Error(\"Illegal attachments\");\n }\n p.attachments = Number(buf);\n }\n // look up namespace (if any)\n if (\"/\" === str.charAt(i + 1)) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (\",\" === c)\n break;\n if (i === str.length)\n break;\n }\n p.nsp = str.substring(start, i);\n }\n else {\n p.nsp = \"/\";\n }\n // look up id\n const next = str.charAt(i + 1);\n if (\"\" !== next && Number(next) == next) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (null == c || Number(c) != c) {\n --i;\n break;\n }\n if (i === str.length)\n break;\n }\n p.id = Number(str.substring(start, i + 1));\n }\n // look up json data\n if (str.charAt(++i)) {\n const payload = this.tryParse(str.substr(i));\n if (Decoder.isPayloadValid(p.type, payload)) {\n p.data = payload;\n }\n else {\n throw new Error(\"invalid payload\");\n }\n }\n return p;\n }\n tryParse(str) {\n try {\n return JSON.parse(str, this.reviver);\n }\n catch (e) {\n return false;\n }\n }\n static isPayloadValid(type, payload) {\n switch (type) {\n case PacketType.CONNECT:\n return typeof payload === \"object\";\n case PacketType.DISCONNECT:\n return payload === undefined;\n case PacketType.CONNECT_ERROR:\n return typeof payload === \"string\" || typeof payload === \"object\";\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n return Array.isArray(payload) && payload.length > 0;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n return Array.isArray(payload);\n }\n }\n /**\n * Deallocates a parser's resources\n */\n destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }\n}\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n constructor(packet) {\n this.packet = packet;\n this.buffers = [];\n this.reconPack = packet;\n }\n /**\n * Method to be called when binary data received from connection\n * after a BINARY_EVENT packet.\n *\n * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n * @return {null | Object} returns null if more binary data is expected or\n * a reconstructed packet object if all buffers have been received.\n */\n takeBinaryData(binData) {\n this.buffers.push(binData);\n if (this.buffers.length === this.reconPack.attachments) {\n // done with buffer list\n const packet = reconstructPacket(this.reconPack, this.buffers);\n this.finishedReconstruction();\n return packet;\n }\n return null;\n }\n /**\n * Cleans up binary packet reconstruction variables.\n */\n finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }\n}\n","export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n","import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n *\n * @public\n */\n constructor(io, nsp, opts) {\n super();\n this.connected = false;\n this.receiveBuffer = [];\n this.sendBuffer = [];\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @public\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for connect()\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * @return self\n * @public\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @return self\n * @public\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev + '\" is a reserved event name');\n }\n args.unshift(ev);\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n const timeout = this.flags.timeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: PacketType.CONNECT, data: this.auth });\n }\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n const id = packet.data.sid;\n this.onconnect(id);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id) {\n this.id = id;\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually.\n *\n * @return self\n * @public\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for disconnect()\n *\n * @return self\n * @public\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n * @public\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @returns self\n * @public\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * ```\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n * ```\n *\n * @returns self\n * @public\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n * @public\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n * @public\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n * @public\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n *\n *
\n     *\n     * socket.onAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n *\n *
\n     *\n     * socket.prependAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n *\n *
\n     *\n     * const handler = (event, ...args) => {\n     *   console.log(event);\n     * }\n     *\n     * socket.onAnyOutgoing(handler);\n     *\n     * // then later\n     * socket.offAnyOutgoing(handler);\n     *\n     * 
\n *\n * @public\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n","/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n","import { Socket as Engine, installTimerFunctions, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n this.decoder.add(data);\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n this.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n","import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","isView","obj","buffer","encodePacket","supportsBinary","callback","encodeBlobAsBase64","fileReader","FileReader","onload","content","result","split","readAsDataURL","lookup","i","decode","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","packetType","length","decoded","base64","SEPARATOR","String","fromCharCode","encodePayload","packets","encodedPackets","Array","count","packet","join","decodePayload","encodedPayload","decodedPacket","push","protocol","Emitter","mixin","on","addEventListener","event","fn","_callbacks","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","callbacks","cb","splice","emit","args","slice","len","emitReserved","listeners","hasListeners","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","BASE64_OVERHEAD","byteLength","utf8Length","Math","ceil","size","str","c","l","charCodeAt","TransportError","reason","description","context","Error","Transport","writable","query","readyState","socket","doOpen","doClose","onClose","write","onPacket","details","alphabet","map","seed","prev","encode","num","encoded","floor","yeast","now","Date","encodeURIComponent","qs","qry","pairs","pair","decodeURIComponent","value","XMLHttpRequest","err","hasCORS","xdomain","e","concat","empty","hasXHR2","xhr","responseType","Polling","polling","location","isSSL","port","xd","hostname","xs","secure","forceBase64","poll","onPause","pause","total","doPoll","onOpen","close","doWrite","schema","timestampRequests","timestampParam","sid","b64","Number","encodedQuery","ipv6","indexOf","path","Request","uri","req","request","method","xhrStatus","onError","onData","pollXhr","async","undefined","xscheme","open","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","onLoad","send","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","terminationEvent","nextTick","isPromiseAvailable","Promise","resolve","then","WebSocket","MozWebSocket","usingBrowserWebSocket","defaultBinaryType","isReactNative","navigator","product","toLowerCase","WS","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","name","transports","websocket","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","queryKey","regx","names","substr","$0","$1","$2","Socket","writeBuffer","prevBufferLen","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","EIO","priorWebsocketSuccess","createTransport","shift","setTransport","onDrain","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","probe","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","shouldCheckPayloadSize","payloadSize","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j","url","loc","test","href","withNativeFile","File","isBinary","hasBinary","toJSON","isArray","deconstructPacket","buffers","packetData","pack","_deconstructPacket","attachments","placeholder","_placeholder","newData","reconstructPacket","_reconstructPacket","PacketType","Encoder","replacer","EVENT","ACK","BINARY_EVENT","BINARY_ACK","encodeAsBinary","encodeAsString","nsp","stringify","deconstruction","unshift","Decoder","reviver","decodeString","reconstructor","BinaryReconstructor","takeBinaryData","p","start","buf","next","payload","tryParse","isPayloadValid","finishedReconstruction","CONNECT","DISCONNECT","CONNECT_ERROR","reconPack","binData","subDestroy","RESERVED_EVENTS","freeze","connect","connect_error","disconnect","disconnecting","newListener","io","connected","receiveBuffer","sendBuffer","ids","acks","flags","auth","_autoConnect","subs","onpacket","subEvents","_readyState","ack","pop","_registerAckCallback","isTransportWritable","engine","discardPacket","notifyOutgoingListeners","timer","_packet","sameNamespace","onconnect","onevent","onack","ondisconnect","destroy","message","emitEvent","_anyListeners","listener","sent","emitBuffered","_anyOutgoingListeners","Backoff","ms","min","max","factor","jitter","attempts","duration","pow","rand","random","deviation","reset","setMin","setMax","setJitter","Manager","_a","nsps","reconnection","reconnectionAttempts","Infinity","reconnectionDelay","reconnectionDelayMax","randomizationFactor","backoff","_parser","parser","encoder","decoder","autoConnect","v","_reconnection","_reconnectionAttempts","_reconnectionDelay","_randomizationFactor","_reconnectionDelayMax","_timeout","_reconnecting","reconnect","Engine","skipReconnect","openSubDestroy","errorSub","maybeReconnectOnOpen","onping","ondata","ondecoded","add","active","_close","delay","onreconnect","attempt","cache","parsed","newConnection","forceNew","multiplex"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA,IAAMA,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAc,IAAd,CAArB;;EACAF,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,OAAD,CAAZ,GAAwB,GAAxB;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB,GAAvB;EACAA,YAAY,CAAC,SAAD,CAAZ,GAA0B,GAA1B;EACAA,YAAY,CAAC,SAAD,CAAZ,GAA0B,GAA1B;EACAA,YAAY,CAAC,MAAD,CAAZ,GAAuB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nK,EAAAA,MAAM,EAANA,MAFkB;EAGlBgH,EAAAA,EAAE,EAAEjW,MAHc;EAIlB4V,EAAAA,OAAO,EAAE5V;EAJS,CAAtB;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/socket.io-client/dist/socket.io.min.js b/node_modules/socket.io-client/dist/socket.io.min.js new file mode 100644 index 0000000..e627c13 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.min.js @@ -0,0 +1,7 @@ +/*! + * Socket.IO v4.5.1 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).io=e()}(this,(function(){"use strict";function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var g=Object.create(null);g.open="0",g.close="1",g.ping="2",g.pong="3",g.message="4",g.upgrade="5",g.noop="6";var m=Object.create(null);Object.keys(g).forEach((function(t){m[g[t]]=t}));for(var k={type:"error",data:"parser error"},b="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),w="function"==typeof ArrayBuffer,_=function(t,e,n){var r,i=t.type,o=t.data;return b&&o instanceof Blob?e?n(o):A(o,n):w&&(o instanceof ArrayBuffer||(r=o,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer))?e?n(o):A(new Blob([o]),n):n(g[i]+(o||""))},A=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];e("b"+t)},n.readAsDataURL(t)},E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",O="undefined"==typeof Uint8Array?[]:new Uint8Array(256),R=0;R1?{type:m[n],data:t.substring(1)}:{type:m[n]}:k},B=function(t,e){if(T){var n=function(t){var e,n,r,i,o,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);var u=new ArrayBuffer(s),h=new Uint8Array(u);for(e=0;e>4,h[c++]=(15&r)<<4|i>>2,h[c++]=(3&i)<<6|63&o;return u}(t);return S(n,e)}return{base64:!0,data:t}},S=function(t,e){return"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t},N=String.fromCharCode(30);function x(t){if(t)return function(t){for(var e in x.prototype)t[e]=x.prototype[e];return t}(t)}x.prototype.on=x.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},x.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},x.prototype.off=x.prototype.removeListener=x.prototype.removeAllListeners=x.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i1?e-1:0),r=1;r0);return e}function z(){var t=Y(+new Date);return t!==D?(H=0,D=t):t+"."+Y(H++)}for(;K<64;K++)V[U[K]]=K;function W(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function $(t){for(var e={},n=t.split("&"),r=0,i=n.length;r0&&void 0!==arguments[0]?arguments[0]:{};return i(t,{xd:this.xd,xs:this.xs},this.opts),new et(this.uri(),t)}},{key:"doWrite",value:function(t,e){var n=this,r=this.request({method:"POST",data:t});r.on("success",e),r.on("error",(function(t,e){n.onError("xhr post error",t,e)}))}},{key:"doPoll",value:function(){var t=this,e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(function(e,n){t.onError("xhr poll error",e,n)})),this.pollXhr=e}}]),s}(M),et=function(t){o(i,t);var n=p(i);function i(t,r){var o;return e(this,i),I(f(o=n.call(this)),r),o.opts=r,o.method=r.method||"GET",o.uri=t,o.async=!1!==r.async,o.data=void 0!==r.data?r.data:null,o.create(),o}return r(i,[{key:"create",value:function(){var t=this,e=P(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;var n=this.xhr=new G(e);try{n.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders)for(var r in n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this.opts.extraHeaders[r])}catch(t){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=function(){4===n.readyState&&(200===n.status||1223===n.status?t.onLoad():t.setTimeoutFn((function(){t.onError("number"==typeof n.status?n.status:0)}),0))},n.send(this.data)}catch(e){return void this.setTimeoutFn((function(){t.onError(e)}),0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)}},{key:"onError",value:function(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Q,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),i}(x);if(et.requestsCount=0,et.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",nt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in L?"pagehide":"unload",nt,!1)}function nt(){for(var t in et.requests)et.requests.hasOwnProperty(t)&&et.requests[t].abort()}var rt="function"==typeof Promise&&"function"==typeof Promise.resolve?function(t){return Promise.resolve().then(t)}:function(t,e){return e(t,0)},it=L.WebSocket||L.MozWebSocket,ot="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),st=function(t){o(i,t);var n=p(i);function i(t){var r;return e(this,i),(r=n.call(this,t)).supportsBinary=!t.forceBase64,r}return r(i,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=ot?{}:P(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=ot?new it(t,e,n):e?new it(t,e):new it(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen()},this.ws.onclose=function(e){return t.onClose({description:"websocket connection closed",context:e})},this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError("websocket error",e)}}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var n=function(n){var r=t[n],i=n===t.length-1;_(r,e.supportsBinary,(function(t){try{e.ws.send(t)}catch(t){}i&&rt((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;r1&&void 0!==arguments[1]?arguments[1]:{};return e(this,a),r=s.call(this),n&&"object"===t(n)&&(o=n,n=null),n?(n=ht(n),o.hostname=n.host,o.secure="https"===n.protocol||"wss"===n.protocol,o.port=n.port,n.query&&(o.query=n.query)):o.host&&(o.hostname=ht(o.host).host),I(f(r),o),r.secure=null!=o.secure?o.secure:"undefined"!=typeof location&&"https:"===location.protocol,o.hostname&&!o.port&&(o.port=r.secure?"443":"80"),r.hostname=o.hostname||("undefined"!=typeof location?location.hostname:"localhost"),r.port=o.port||("undefined"!=typeof location&&location.port?location.port:r.secure?"443":"80"),r.transports=o.transports||["polling","websocket"],r.readyState="",r.writeBuffer=[],r.prevBufferLen=0,r.opts=i({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},o),r.opts.path=r.opts.path.replace(/\/$/,"")+"/","string"==typeof r.opts.query&&(r.opts.query=$(r.opts.query)),r.id=null,r.upgrades=null,r.pingInterval=null,r.pingTimeout=null,r.pingTimeoutTimer=null,"function"==typeof addEventListener&&(r.opts.closeOnBeforeunload&&addEventListener("beforeunload",(function(){r.transport&&(r.transport.removeAllListeners(),r.transport.close())}),!1),"localhost"!==r.hostname&&(r.offlineEventListener=function(){r.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",r.offlineEventListener,!1))),r.open(),r}return r(a,[{key:"createTransport",value:function(t){var e=i({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);var n=i({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new at[t](n)}},{key:"open",value:function(){var t,e=this;if(this.opts.rememberUpgrade&&a.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((function(){e.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}},{key:"setTransport",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(function(t){return e.onClose("transport close",t)}))}},{key:"probe",value:function(t){var e=this,n=this.createTransport(t),r=!1;a.priorWebsocketSuccess=!1;var i=function(){r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",(function(t){if(!r)if("pong"===t.type&&"probe"===t.data){if(e.upgrading=!0,e.emitReserved("upgrading",n),!n)return;a.priorWebsocketSuccess="websocket"===n.name,e.transport.pause((function(){r||"closed"!==e.readyState&&(f(),e.setTransport(n),n.send([{type:"upgrade"}]),e.emitReserved("upgrade",n),n=null,e.upgrading=!1,e.flush())}))}else{var i=new Error("probe error");i.transport=n.name,e.emitReserved("upgradeError",i)}})))};function o(){r||(r=!0,f(),n.close(),n=null)}var s=function(t){var r=new Error("probe error: "+t);r.transport=n.name,o(),e.emitReserved("upgradeError",r)};function c(){s("transport closed")}function u(){s("socket closed")}function h(t){n&&t.name!==n.name&&o()}var f=function(){n.removeListener("open",i),n.removeListener("error",s),n.removeListener("close",c),e.off("close",u),e.off("upgrading",h)};n.once("open",i),n.once("error",s),n.once("close",c),this.once("close",u),this.once("upgrading",h),n.open()}},{key:"onOpen",value:function(){if(this.readyState="open",a.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t1))return this.writeBuffer;for(var t,e=1,n=0;n=57344?n+=3:(r++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}},{key:"write",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"send",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"sendPacket",value:function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}}},{key:"close",value:function(){var t=this,e=function(){t.onClose("forced close"),t.transport.close()},n=function n(){t.off("upgrade",n),t.off("upgradeError",n),e()},r=function(){t.once("upgrade",n),t.once("upgradeError",n)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){t.upgrading?r():e()})):this.upgrading?r():e()),this}},{key:"onError",value:function(t){a.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}},{key:"onClose",value:function(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(t){for(var e=[],n=0,r=t.length;n0;case _t.ACK:case _t.BINARY_ACK:return Array.isArray(n)}}}]),a}(x),Ot=function(){function t(n){e(this,t),this.packet=n,this.buffers=[],this.reconPack=n}return r(t,[{key:"takeBinaryData",value:function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=bt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}},{key:"finishedReconstruction",value:function(){this.reconPack=null,this.buffers=[]}}]),t}(),Rt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return _t},Encoder:At,Decoder:Et});function Tt(t,e,n){return t.on(e,n),function(){t.off(e,n)}}var Ct=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Bt=function(t){o(i,t);var n=p(i);function i(t,r,o){var s;return e(this,i),(s=n.call(this)).connected=!1,s.receiveBuffer=[],s.sendBuffer=[],s.ids=0,s.acks={},s.flags={},s.io=t,s.nsp=r,o&&o.auth&&(s.auth=o.auth),s.io._autoConnect&&s.open(),s}return r(i,[{key:"disconnected",get:function(){return!this.connected}},{key:"subEvents",value:function(){if(!this.subs){var t=this.io;this.subs=[Tt(t,"open",this.onopen.bind(this)),Tt(t,"packet",this.onpacket.bind(this)),Tt(t,"error",this.onerror.bind(this)),Tt(t,"close",this.onclose.bind(this))]}}},{key:"active",get:function(){return!!this.subs}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n1?e-1:0),r=1;r0&&t.jitter<=1?t.jitter:0,this.attempts=0}St.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},St.prototype.reset=function(){this.attempts=0},St.prototype.setMin=function(t){this.ms=t},St.prototype.setMax=function(t){this.max=t},St.prototype.setJitter=function(t){this.jitter=t};var Nt=function(n){o(s,n);var i=p(s);function s(n,r){var o,a;e(this,s),(o=i.call(this)).nsps={},o.subs=[],n&&"object"===t(n)&&(r=n,n=void 0),(r=r||{}).path=r.path||"/socket.io",o.opts=r,I(f(o),r),o.reconnection(!1!==r.reconnection),o.reconnectionAttempts(r.reconnectionAttempts||1/0),o.reconnectionDelay(r.reconnectionDelay||1e3),o.reconnectionDelayMax(r.reconnectionDelayMax||5e3),o.randomizationFactor(null!==(a=r.randomizationFactor)&&void 0!==a?a:.5),o.backoff=new St({min:o.reconnectionDelay(),max:o.reconnectionDelayMax(),jitter:o.randomizationFactor()}),o.timeout(null==r.timeout?2e4:r.timeout),o._readyState="closed",o.uri=n;var c=r.parser||Rt;return o.encoder=new c.Encoder,o.decoder=new c.Decoder,o._autoConnect=!1!==r.autoConnect,o._autoConnect&&o.open(),o}return r(s,[{key:"reconnection",value:function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}},{key:"reconnectionAttempts",value:function(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}},{key:"reconnectionDelay",value:function(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}},{key:"randomizationFactor",value:function(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}},{key:"reconnectionDelayMax",value:function(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}},{key:"timeout",value:function(t){return arguments.length?(this._timeout=t,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(t){var e=this;if(~this._readyState.indexOf("open"))return this;this.engine=new ft(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var i=Tt(n,"open",(function(){r.onopen(),t&&t()})),o=Tt(n,"error",(function(n){r.cleanup(),r._readyState="closed",e.emitReserved("error",n),t?t(n):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var s=this._timeout;0===s&&i();var a=this.setTimeoutFn((function(){i(),n.close(),n.emit("error",new Error("timeout"))}),s);this.opts.autoUnref&&a.unref(),this.subs.push((function(){clearTimeout(a)}))}return this.subs.push(i),this.subs.push(o),this}},{key:"connect",value:function(t){return this.open(t)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",this.emitReserved("open");var t=this.engine;this.subs.push(Tt(t,"ping",this.onping.bind(this)),Tt(t,"data",this.ondata.bind(this)),Tt(t,"error",this.onerror.bind(this)),Tt(t,"close",this.onclose.bind(this)),Tt(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){this.emitReserved("ping")}},{key:"ondata",value:function(t){this.decoder.add(t)}},{key:"ondecoded",value:function(t){this.emitReserved("packet",t)}},{key:"onerror",value:function(t){this.emitReserved("error",t)}},{key:"socket",value:function(t,e){var n=this.nsps[t];return n||(n=new Bt(this,t,e),this.nsps[t]=n),n}},{key:"_destroy",value:function(t){for(var e=0,n=Object.keys(this.nsps);e=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{var n=this.backoff.duration();this._reconnecting=!0;var r=this.setTimeoutFn((function(){e.skipReconnect||(t.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((function(n){n?(e._reconnecting=!1,e.reconnect(),t.emitReserved("reconnect_error",n)):e.onreconnect()})))}),n);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}},{key:"onreconnect",value:function(){var t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}]),s}(x),xt={};function Lt(e,n){"object"===t(e)&&(n=e,e=void 0);var r,i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0,r=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),r=ht(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(e,(n=n||{}).path||"/socket.io"),o=i.source,s=i.id,a=i.path,c=xt[s]&&a in xt[s].nsps;return n.forceNew||n["force new connection"]||!1===n.multiplex||c?r=new Nt(o,n):(xt[s]||(xt[s]=new Nt(o,n)),r=xt[s]),i.query&&!n.query&&(n.query=i.queryKey),r.socket(i.path,n)}return i(Lt,{Manager:Nt,Socket:Bt,io:Lt,connect:Lt}),Lt})); +//# sourceMappingURL=socket.io.min.js.map diff --git a/node_modules/socket.io-client/dist/socket.io.min.js.map b/node_modules/socket.io-client/dist/socket.io.min.js.map new file mode 100644 index 0000000..ace1b4d --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socket.io.min.js","sources":["../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/commons.js","../node_modules/@socket.io/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/encodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/decodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/index.js","../node_modules/@socket.io/component-emitter/index.mjs","../node_modules/engine.io-client/build/esm/globalThis.browser.js","../node_modules/engine.io-client/build/esm/util.js","../node_modules/engine.io-client/build/esm/contrib/yeast.js","../node_modules/engine.io-client/build/esm/transport.js","../node_modules/engine.io-client/build/esm/contrib/parseqs.js","../node_modules/engine.io-client/build/esm/contrib/has-cors.js","../node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js","../node_modules/engine.io-client/build/esm/transports/polling.js","../node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js","../node_modules/engine.io-client/build/esm/transports/websocket.js","../node_modules/engine.io-client/build/esm/transports/index.js","../node_modules/engine.io-client/build/esm/contrib/parseuri.js","../node_modules/engine.io-client/build/esm/socket.js","../node_modules/socket.io-parser/build/esm/is-binary.js","../node_modules/socket.io-parser/build/esm/binary.js","../node_modules/socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export default (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import globalThis from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport globalThis from \"../globalThis.js\";\nexport default function (opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport XMLHttpRequest from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport globalThis from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import globalThis from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return (!!WebSocket &&\n !(\"__initialize\" in WebSocket && this.name === WS.prototype.name));\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","const withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n (typeof File !== \"undefined\" &&\n toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nexport function isBinary(obj) {\n return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n (withNativeBlob && obj instanceof Blob) ||\n (withNativeFile && obj instanceof File));\n}\nexport function hasBinary(obj, toJSON) {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n if (Array.isArray(obj)) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (hasBinary(obj[i])) {\n return true;\n }\n }\n return false;\n }\n if (isBinary(obj)) {\n return true;\n }\n if (obj.toJSON &&\n typeof obj.toJSON === \"function\" &&\n arguments.length === 1) {\n return hasBinary(obj.toJSON(), true);\n }\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n return true;\n }\n }\n return false;\n}\n","import { isBinary } from \"./is-binary.js\";\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nexport function deconstructPacket(packet) {\n const buffers = [];\n const packetData = packet.data;\n const pack = packet;\n pack.data = _deconstructPacket(packetData, buffers);\n pack.attachments = buffers.length; // number of binary 'attachments'\n return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (isBinary(data)) {\n const placeholder = { _placeholder: true, num: buffers.length };\n buffers.push(data);\n return placeholder;\n }\n else if (Array.isArray(data)) {\n const newData = new Array(data.length);\n for (let i = 0; i < data.length; i++) {\n newData[i] = _deconstructPacket(data[i], buffers);\n }\n return newData;\n }\n else if (typeof data === \"object\" && !(data instanceof Date)) {\n const newData = {};\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n newData[key] = _deconstructPacket(data[key], buffers);\n }\n }\n return newData;\n }\n return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nexport function reconstructPacket(packet, buffers) {\n packet.data = _reconstructPacket(packet.data, buffers);\n packet.attachments = undefined; // no longer useful\n return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n if (!data)\n return data;\n if (data && data._placeholder) {\n return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n }\n else if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n data[i] = _reconstructPacket(data[i], buffers);\n }\n }\n else if (typeof data === \"object\") {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n data[key] = _reconstructPacket(data[key], buffers);\n }\n }\n }\n return data;\n}\n","import { Emitter } from \"@socket.io/component-emitter\";\nimport { deconstructPacket, reconstructPacket } from \"./binary.js\";\nimport { isBinary, hasBinary } from \"./is-binary.js\";\n/**\n * Protocol version.\n *\n * @public\n */\nexport const protocol = 5;\nexport var PacketType;\n(function (PacketType) {\n PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nexport class Encoder {\n /**\n * Encoder constructor\n *\n * @param {function} replacer - custom replacer to pass down to JSON.parse\n */\n constructor(replacer) {\n this.replacer = replacer;\n }\n /**\n * Encode a packet as a single string if non-binary, or as a\n * buffer sequence, depending on packet type.\n *\n * @param {Object} obj - packet object\n */\n encode(obj) {\n if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n if (hasBinary(obj)) {\n obj.type =\n obj.type === PacketType.EVENT\n ? PacketType.BINARY_EVENT\n : PacketType.BINARY_ACK;\n return this.encodeAsBinary(obj);\n }\n }\n return [this.encodeAsString(obj)];\n }\n /**\n * Encode packet as string.\n */\n encodeAsString(obj) {\n // first is type\n let str = \"\" + obj.type;\n // attachments if we have them\n if (obj.type === PacketType.BINARY_EVENT ||\n obj.type === PacketType.BINARY_ACK) {\n str += obj.attachments + \"-\";\n }\n // if we have a namespace other than `/`\n // we append it followed by a comma `,`\n if (obj.nsp && \"/\" !== obj.nsp) {\n str += obj.nsp + \",\";\n }\n // immediately followed by the id\n if (null != obj.id) {\n str += obj.id;\n }\n // json data\n if (null != obj.data) {\n str += JSON.stringify(obj.data, this.replacer);\n }\n return str;\n }\n /**\n * Encode packet as 'buffer sequence' by removing blobs, and\n * deconstructing packet into object with placeholders and\n * a list of buffers.\n */\n encodeAsBinary(obj) {\n const deconstruction = deconstructPacket(obj);\n const pack = this.encodeAsString(deconstruction.packet);\n const buffers = deconstruction.buffers;\n buffers.unshift(pack); // add packet info to beginning of data list\n return buffers; // write all the buffers\n }\n}\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nexport class Decoder extends Emitter {\n /**\n * Decoder constructor\n *\n * @param {function} reviver - custom reviver to pass down to JSON.stringify\n */\n constructor(reviver) {\n super();\n this.reviver = reviver;\n }\n /**\n * Decodes an encoded packet string into packet JSON.\n *\n * @param {String} obj - encoded packet\n */\n add(obj) {\n let packet;\n if (typeof obj === \"string\") {\n packet = this.decodeString(obj);\n if (packet.type === PacketType.BINARY_EVENT ||\n packet.type === PacketType.BINARY_ACK) {\n // binary packet's json\n this.reconstructor = new BinaryReconstructor(packet);\n // no attachments, labeled binary but no binary data to follow\n if (packet.attachments === 0) {\n super.emitReserved(\"decoded\", packet);\n }\n }\n else {\n // non-binary full packet\n super.emitReserved(\"decoded\", packet);\n }\n }\n else if (isBinary(obj) || obj.base64) {\n // raw binary data\n if (!this.reconstructor) {\n throw new Error(\"got binary data when not reconstructing a packet\");\n }\n else {\n packet = this.reconstructor.takeBinaryData(obj);\n if (packet) {\n // received final buffer\n this.reconstructor = null;\n super.emitReserved(\"decoded\", packet);\n }\n }\n }\n else {\n throw new Error(\"Unknown type: \" + obj);\n }\n }\n /**\n * Decode a packet String (JSON data)\n *\n * @param {String} str\n * @return {Object} packet\n */\n decodeString(str) {\n let i = 0;\n // look up type\n const p = {\n type: Number(str.charAt(0)),\n };\n if (PacketType[p.type] === undefined) {\n throw new Error(\"unknown packet type \" + p.type);\n }\n // look up attachments if type binary\n if (p.type === PacketType.BINARY_EVENT ||\n p.type === PacketType.BINARY_ACK) {\n const start = i + 1;\n while (str.charAt(++i) !== \"-\" && i != str.length) { }\n const buf = str.substring(start, i);\n if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n throw new Error(\"Illegal attachments\");\n }\n p.attachments = Number(buf);\n }\n // look up namespace (if any)\n if (\"/\" === str.charAt(i + 1)) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (\",\" === c)\n break;\n if (i === str.length)\n break;\n }\n p.nsp = str.substring(start, i);\n }\n else {\n p.nsp = \"/\";\n }\n // look up id\n const next = str.charAt(i + 1);\n if (\"\" !== next && Number(next) == next) {\n const start = i + 1;\n while (++i) {\n const c = str.charAt(i);\n if (null == c || Number(c) != c) {\n --i;\n break;\n }\n if (i === str.length)\n break;\n }\n p.id = Number(str.substring(start, i + 1));\n }\n // look up json data\n if (str.charAt(++i)) {\n const payload = this.tryParse(str.substr(i));\n if (Decoder.isPayloadValid(p.type, payload)) {\n p.data = payload;\n }\n else {\n throw new Error(\"invalid payload\");\n }\n }\n return p;\n }\n tryParse(str) {\n try {\n return JSON.parse(str, this.reviver);\n }\n catch (e) {\n return false;\n }\n }\n static isPayloadValid(type, payload) {\n switch (type) {\n case PacketType.CONNECT:\n return typeof payload === \"object\";\n case PacketType.DISCONNECT:\n return payload === undefined;\n case PacketType.CONNECT_ERROR:\n return typeof payload === \"string\" || typeof payload === \"object\";\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n return Array.isArray(payload) && payload.length > 0;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n return Array.isArray(payload);\n }\n }\n /**\n * Deallocates a parser's resources\n */\n destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }\n}\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n constructor(packet) {\n this.packet = packet;\n this.buffers = [];\n this.reconPack = packet;\n }\n /**\n * Method to be called when binary data received from connection\n * after a BINARY_EVENT packet.\n *\n * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n * @return {null | Object} returns null if more binary data is expected or\n * a reconstructed packet object if all buffers have been received.\n */\n takeBinaryData(binData) {\n this.buffers.push(binData);\n if (this.buffers.length === this.reconPack.attachments) {\n // done with buffer list\n const packet = reconstructPacket(this.reconPack, this.buffers);\n this.finishedReconstruction();\n return packet;\n }\n return null;\n }\n /**\n * Cleans up binary packet reconstruction variables.\n */\n finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }\n}\n","export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n","import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n *\n * @public\n */\n constructor(io, nsp, opts) {\n super();\n this.connected = false;\n this.receiveBuffer = [];\n this.sendBuffer = [];\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @public\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for connect()\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * @return self\n * @public\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @return self\n * @public\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev + '\" is a reserved event name');\n }\n args.unshift(ev);\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n const timeout = this.flags.timeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: PacketType.CONNECT, data: this.auth });\n }\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n const id = packet.data.sid;\n this.onconnect(id);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id) {\n this.id = id;\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually.\n *\n * @return self\n * @public\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for disconnect()\n *\n * @return self\n * @public\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n * @public\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @returns self\n * @public\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * ```\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n * ```\n *\n * @returns self\n * @public\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n * @public\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n * @public\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n * @public\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n *\n *
\n     *\n     * socket.onAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n *\n *
\n     *\n     * socket.prependAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n *\n *
\n     *\n     * const handler = (event, ...args) => {\n     *   console.log(event);\n     * }\n     *\n     * socket.onAnyOutgoing(handler);\n     *\n     * // then later\n     * socket.offAnyOutgoing(handler);\n     *\n     * 
\n *\n * @public\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n","/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n","import { Socket as Engine, installTimerFunctions, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n this.decoder.add(data);\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n this.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n","import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n","import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","encodePacket","supportsBinary","callback","obj","encodeBlobAsBase64","isView","buffer","fileReader","FileReader","onload","content","result","split","readAsDataURL","chars","lookup","Uint8Array","i","length","charCodeAt","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","decoded","base64","encoded1","encoded2","encoded3","encoded4","bufferLength","len","p","arraybuffer","bytes","decode","SEPARATOR","String","fromCharCode","Emitter","mixin","on","addEventListener","event","fn","_callbacks","this","push","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","cb","callbacks","splice","emit","args","Array","slice","emitReserved","listeners","hasListeners","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","prev","TransportError","reason","description","context","Error","Transport","writable","query","readyState","socket","doOpen","doClose","onClose","packets","write","packet","onPacket","details","alphabet","map","seed","encode","num","encoded","Math","floor","yeast","now","Date","str","encodeURIComponent","qs","qry","pairs","l","pair","decodeURIComponent","value","XMLHttpRequest","err","hasCORS","xdomain","e","concat","join","empty","hasXHR2","responseType","Polling","polling","location","isSSL","protocol","port","xd","hostname","xs","secure","forceBase64","poll","onPause","pause","_this2","total","doPoll","encodedPayload","encodedPackets","decodedPacket","decodePayload","_this3","onOpen","close","_this4","count","encodePayload","_this5","doWrite","schema","timestampRequests","timestampParam","sid","b64","Number","encodedQuery","indexOf","path","Request","uri","req","request","method","xhrStatus","_this6","onError","onData","_this7","pollXhr","async","undefined","xscheme","xhr","open","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","_this9","onLoad","send","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","nextTick","Promise","resolve","then","WebSocket","MozWebSocket","isReactNative","navigator","product","toLowerCase","WS","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","name","transports","websocket","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","regx","names","substr","queryKey","$0","$1","$2","Socket","_this","writeBuffer","prevBufferLen","_extends","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","EIO","priorWebsocketSuccess","createTransport","shift","setTransport","onDrain","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","probe","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","payloadSize","c","utf8Length","ceil","byteLength","size","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j","withNativeFile","File","isBinary","hasBinary","toJSON","_typeof","isArray","deconstructPacket","buffers","packetData","pack","_deconstructPacket","attachments","placeholder","_placeholder","newData","reconstructPacket","_reconstructPacket","PacketType","Encoder","replacer","EVENT","ACK","encodeAsString","BINARY_EVENT","BINARY_ACK","encodeAsBinary","nsp","stringify","deconstruction","unshift","Decoder","reviver","decodeString","reconstructor","BinaryReconstructor","takeBinaryData","start","buf","next","payload","tryParse","isPayloadValid","finishedReconstruction","CONNECT","DISCONNECT","CONNECT_ERROR","reconPack","binData","RESERVED_EVENTS","freeze","connect","connect_error","disconnect","disconnecting","newListener","io","connected","receiveBuffer","sendBuffer","ids","acks","flags","auth","_autoConnect","subs","onpacket","subEvents","_readyState","ack","pop","_registerAckCallback","isTransportWritable","engine","discardPacket","notifyOutgoingListeners","timer","_packet","onconnect","onevent","onack","ondisconnect","destroy","message","emitEvent","_anyListeners","sent","emitBuffered","subDestroy","listener","_anyOutgoingListeners","Backoff","ms","min","max","factor","jitter","attempts","duration","pow","rand","random","deviation","reset","setMin","setMax","setJitter","Manager","_a","nsps","reconnection","reconnectionAttempts","Infinity","reconnectionDelay","reconnectionDelayMax","randomizationFactor","backoff","_parser","parser","encoder","decoder","autoConnect","v","_reconnection","_reconnectionAttempts","_reconnectionDelay","_randomizationFactor","_reconnectionDelayMax","_timeout","_reconnecting","reconnect","Engine","skipReconnect","openSubDestroy","errorSub","maybeReconnectOnOpen","onping","ondata","ondecoded","add","active","_close","delay","onreconnect","attempt","cache","parsed","loc","test","href","url","sameNamespace","forceNew","multiplex"],"mappings":";;;;;glIAAA,IAAMA,EAAeC,OAAOC,OAAO,MACnCF,EAAY,KAAW,IACvBA,EAAY,MAAY,IACxBA,EAAY,KAAW,IACvBA,EAAY,KAAW,IACvBA,EAAY,QAAc,IAC1BA,EAAY,QAA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AAMnE,IAGX7K,EAAI2I,OACD,cAAcoU,KAAK/c,EAAI0I,UACvB1I,EAAI2I,KAAO,KAEN,eAAeoU,KAAK/c,EAAI0I,YAC7B1I,EAAI2I,KAAO,QAGnB3I,EAAI2K,KAAO3K,EAAI2K,MAAQ,QAEjB4E,GADkC,IAA3BvP,EAAIuP,KAAK7E,QAAQ,KACV,IAAM1K,EAAIuP,KAAO,IAAMvP,EAAIuP,YAE/CvP,EAAI+Q,GAAK/Q,EAAI0I,SAAW,MAAQ6G,EAAO,IAAMvP,EAAI2I,KAAOgC,EAExD3K,EAAIgd,KACAhd,EAAI0I,SACA,MACA6G,GACCuN,GAAOA,EAAInU,OAAS3I,EAAI2I,KAAO,GAAK,IAAM3I,EAAI2I,MAChD3I,ED5CQid,CAAIpS,GADnB9F,EAAOA,GAAQ,IACc4F,MAAQ,cAC/B2E,EAASuN,EAAOvN,OAChByB,EAAK8L,EAAO9L,GACZpG,EAAOkS,EAAOlS,KACduS,EAAgBN,GAAM7L,IAAOpG,KAAQiS,GAAM7L,GAAN,YACrBhM,EAAKoY,UACvBpY,EAAK,0BACL,IAAUA,EAAKqY,WACfF,EAGA/F,EAAK,IAAImD,GAAQhL,EAAQvK,IAGpB6X,GAAM7L,KACP6L,GAAM7L,GAAM,IAAIuJ,GAAQhL,EAAQvK,IAEpCoS,EAAKyF,GAAM7L,IAEX8L,EAAOhX,QAAUd,EAAKc,QACtBd,EAAKc,MAAQgX,EAAO/M,UAEjBqH,EAAGpR,OAAO8W,EAAOlS,KAAM5F,UAIlCuL,EAAc1P,GAAQ,CAClB0Z,QAAAA,GACApK,OAAAA,GACAiH,GAAIvW,GACJkW,QAASlW"} \ No newline at end of file diff --git a/node_modules/socket.io-client/dist/socket.io.msgpack.min.js b/node_modules/socket.io-client/dist/socket.io.msgpack.min.js new file mode 100644 index 0000000..bbfeb55 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.msgpack.min.js @@ -0,0 +1,7 @@ +/*! + * Socket.IO v4.5.1 + * (c) 2014-2022 Guillermo Rauch + * Released under the MIT License. + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).io=e()}(this,(function(){"use strict";function t(t,e){return e.forEach((function(e){Object.keys(e).forEach((function(n){if("default"!==n&&!(n in t)){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}))})),Object.freeze(t)}function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return o=t.done,t},e:function(t){a=!0,s=t},f:function(){try{o||null==n.return||n.return()}finally{if(a)throw s}}}}var m=Object.create(null);m.open="0",m.close="1",m.ping="2",m.pong="3",m.message="4",m.upgrade="5",m.noop="6";var _=Object.create(null);Object.keys(m).forEach((function(t){_[m[t]]=t}));for(var b={type:"error",data:"parser error"},k="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),w="function"==typeof ArrayBuffer,O=function(t,e,n){var r,i=t.type,s=t.data;return k&&s instanceof Blob?e?n(s):E(s,n):w&&(s instanceof ArrayBuffer||(r=s,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer))?e?n(s):E(new Blob([s]),n):n(m[i]+(s||""))},E=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];e("b"+t)},n.readAsDataURL(t)},C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",R="undefined"==typeof Uint8Array?[]:new Uint8Array(256),T=0;T1?{type:_[n],data:t.substring(1)}:{type:_[n]}:b},L=function(t,e){if(S){var n=function(t){var e,n,r,i,s,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);var u=new ArrayBuffer(o),h=new Uint8Array(u);for(e=0;e>4,h[c++]=(15&r)<<4|i>>2,h[c++]=(3&i)<<6|63&s;return u}(t);return x(n,e)}return{base64:!0,data:t}},x=function(t,e){return"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t},B=String.fromCharCode(30);function U(t){if(t)return function(t){for(var e in U.prototype)t[e]=U.prototype[e];return t}(t)}U.prototype.on=U.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},U.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},U.prototype.off=U.prototype.removeListener=U.prototype.removeAllListeners=U.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i1?e-1:0),r=1;r0);return e}function X(){var t=W(+new Date);return t!==D?(z=0,D=t):t+"."+W(z++)}for(;V<64;V++)$[H[V]]=V;function K(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function J(t){for(var e={},n=t.split("&"),r=0,i=n.length;r0&&void 0!==arguments[0]?arguments[0]:{};return s(t,{xd:this.xd,xs:this.xs},this.opts),new nt(this.uri(),t)}},{key:"doWrite",value:function(t,e){var n=this,r=this.request({method:"POST",data:t});r.on("success",e),r.on("error",(function(t,e){n.onError("xhr post error",t,e)}))}},{key:"doPoll",value:function(){var t=this,e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(function(e,n){t.onError("xhr poll error",e,n)})),this.pollXhr=e}}]),r}(F),nt=function(t){o(r,t);var e=d(r);function r(t,i){var s;return n(this,r),M(l(s=e.call(this)),i),s.opts=i,s.method=i.method||"GET",s.uri=t,s.async=!1!==i.async,s.data=void 0!==i.data?i.data:null,s.create(),s}return i(r,[{key:"create",value:function(){var t=this,e=P(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;var n=this.xhr=new Q(e);try{n.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders)for(var i in n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this.opts.extraHeaders[i])}catch(t){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=function(){4===n.readyState&&(200===n.status||1223===n.status?t.onLoad():t.setTimeoutFn((function(){t.onError("number"==typeof n.status?n.status:0)}),0))},n.send(this.data)}catch(e){return void this.setTimeoutFn((function(){t.onError(e)}),0)}"undefined"!=typeof document&&(this.index=r.requestsCount++,r.requests[this.index]=this)}},{key:"onError",value:function(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Z,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete r.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),r}(U);if(nt.requestsCount=0,nt.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",rt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in j?"pagehide":"unload",rt,!1)}function rt(){for(var t in nt.requests)nt.requests.hasOwnProperty(t)&&nt.requests[t].abort()}var it="function"==typeof Promise&&"function"==typeof Promise.resolve?function(t){return Promise.resolve().then(t)}:function(t,e){return e(t,0)},st=j.WebSocket||j.MozWebSocket,ot="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),at=function(t){o(r,t);var e=d(r);function r(t){var i;return n(this,r),(i=e.call(this,t)).supportsBinary=!t.forceBase64,i}return i(r,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=ot?{}:P(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=ot?new st(t,e,n):e?new st(t,e):new st(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen()},this.ws.onclose=function(e){return t.onClose({description:"websocket connection closed",context:e})},this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError("websocket error",e)}}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var n=function(n){var r=t[n],i=n===t.length-1;O(r,e.supportsBinary,(function(t){try{e.ws.send(t)}catch(t){}i&&it((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;r1&&void 0!==arguments[1]?arguments[1]:{};return n(this,a),i=r.call(this),t&&"object"===e(t)&&(o=t,t=null),t?(t=ft(t),o.hostname=t.host,o.secure="https"===t.protocol||"wss"===t.protocol,o.port=t.port,t.query&&(o.query=t.query)):o.host&&(o.hostname=ft(o.host).host),M(l(i),o),i.secure=null!=o.secure?o.secure:"undefined"!=typeof location&&"https:"===location.protocol,o.hostname&&!o.port&&(o.port=i.secure?"443":"80"),i.hostname=o.hostname||("undefined"!=typeof location?location.hostname:"localhost"),i.port=o.port||("undefined"!=typeof location&&location.port?location.port:i.secure?"443":"80"),i.transports=o.transports||["polling","websocket"],i.readyState="",i.writeBuffer=[],i.prevBufferLen=0,i.opts=s({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},o),i.opts.path=i.opts.path.replace(/\/$/,"")+"/","string"==typeof i.opts.query&&(i.opts.query=J(i.opts.query)),i.id=null,i.upgrades=null,i.pingInterval=null,i.pingTimeout=null,i.pingTimeoutTimer=null,"function"==typeof addEventListener&&(i.opts.closeOnBeforeunload&&addEventListener("beforeunload",(function(){i.transport&&(i.transport.removeAllListeners(),i.transport.close())}),!1),"localhost"!==i.hostname&&(i.offlineEventListener=function(){i.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",i.offlineEventListener,!1))),i.open(),i}return i(a,[{key:"createTransport",value:function(t){var e=s({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);var n=s({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new ct[t](n)}},{key:"open",value:function(){var t,e=this;if(this.opts.rememberUpgrade&&a.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((function(){e.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}},{key:"setTransport",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(function(t){return e.onClose("transport close",t)}))}},{key:"probe",value:function(t){var e=this,n=this.createTransport(t),r=!1;a.priorWebsocketSuccess=!1;var i=function(){r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",(function(t){if(!r)if("pong"===t.type&&"probe"===t.data){if(e.upgrading=!0,e.emitReserved("upgrading",n),!n)return;a.priorWebsocketSuccess="websocket"===n.name,e.transport.pause((function(){r||"closed"!==e.readyState&&(f(),e.setTransport(n),n.send([{type:"upgrade"}]),e.emitReserved("upgrade",n),n=null,e.upgrading=!1,e.flush())}))}else{var i=new Error("probe error");i.transport=n.name,e.emitReserved("upgradeError",i)}})))};function s(){r||(r=!0,f(),n.close(),n=null)}var o=function(t){var r=new Error("probe error: "+t);r.transport=n.name,s(),e.emitReserved("upgradeError",r)};function c(){o("transport closed")}function u(){o("socket closed")}function h(t){n&&t.name!==n.name&&s()}var f=function(){n.removeListener("open",i),n.removeListener("error",o),n.removeListener("close",c),e.off("close",u),e.off("upgrading",h)};n.once("open",i),n.once("error",o),n.once("close",c),this.once("close",u),this.once("upgrading",h),n.open()}},{key:"onOpen",value:function(){if(this.readyState="open",a.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t1))return this.writeBuffer;for(var t,e=1,n=0;n=57344?n+=3:(r++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}},{key:"write",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"send",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"sendPacket",value:function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}}},{key:"close",value:function(){var t=this,e=function(){t.onClose("forced close"),t.transport.close()},n=function n(){t.off("upgrade",n),t.off("upgradeError",n),e()},r=function(){t.once("upgrade",n),t.once("upgradeError",n)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){t.upgrading?r():e()})):this.upgrading?r():e()),this}},{key:"onError",value:function(t){a.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}},{key:"onClose",value:function(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(t){for(var e=[],n=0,r=t.length;n>6),t.setUint8(e++,128|63&r)):r<55296||r>=57344?(t.setUint8(e++,224|r>>12),t.setUint8(e++,128|r>>6&63),t.setUint8(e++,128|63&r)):(i++,r=65536+((1023&r)<<10|1023&n.charCodeAt(i)),t.setUint8(e++,240|r>>18),t.setUint8(e++,128|r>>12&63),t.setUint8(e++,128|r>>6&63),t.setUint8(e++,128|63&r))}function vt(t,n,r){var i=e(r),s=0,o=0,a=0,c=0,u=0,h=0;if("string"===i){if(u=function(t){for(var e=0,n=0,r=0,i=t.length;r=57344?n+=3:(r++,n+=4);return n}(r),u<32)t.push(160|u),h=1;else if(u<256)t.push(217,u),h=2;else if(u<65536)t.push(218,u>>8,u),h=3;else{if(!(u<4294967296))throw new Error("String too long");t.push(219,u>>24,u>>16,u>>8,u),h=5}return n.push({_str:r,_length:u,_offset:t.length}),h+u}if("number"===i)return Math.floor(r)===r&&isFinite(r)?r>=0?r<128?(t.push(r),1):r<256?(t.push(204,r),2):r<65536?(t.push(205,r>>8,r),3):r<4294967296?(t.push(206,r>>24,r>>16,r>>8,r),5):(a=r/Math.pow(2,32)>>0,c=r>>>0,t.push(207,a>>24,a>>16,a>>8,a,c>>24,c>>16,c>>8,c),9):r>=-32?(t.push(r),1):r>=-128?(t.push(208,r),2):r>=-32768?(t.push(209,r>>8,r),3):r>=-2147483648?(t.push(210,r>>24,r>>16,r>>8,r),5):(a=Math.floor(r/Math.pow(2,32)),c=r>>>0,t.push(211,a>>24,a>>16,a>>8,a,c>>24,c>>16,c>>8,c),9):(t.push(203),n.push({_float:r,_length:8,_offset:t.length}),9);if("object"===i){if(null===r)return t.push(192),1;if(Array.isArray(r)){if((u=r.length)<16)t.push(144|u),h=1;else if(u<65536)t.push(220,u>>8,u),h=3;else{if(!(u<4294967296))throw new Error("Array too large");t.push(221,u>>24,u>>16,u>>8,u),h=5}for(s=0;s>>0,t.push(215,0,a>>24,a>>16,a>>8,a,c>>24,c>>16,c>>8,c),10}if(r instanceof ArrayBuffer){if((u=r.byteLength)<256)t.push(196,u),h=2;else if(u<65536)t.push(197,u>>8,u),h=3;else{if(!(u<4294967296))throw new Error("Buffer too large");t.push(198,u>>24,u>>16,u>>8,u),h=5}return n.push({_bin:r,_length:u,_offset:t.length}),h+u}if("function"==typeof r.toJSON)return vt(t,n,r.toJSON());var l=[],p="",d=Object.keys(r);for(s=0,o=d.length;s>8,u),h=3;else{if(!(u<4294967296))throw new Error("Object too large");t.push(223,u>>24,u>>16,u>>8,u),h=5}for(s=0;s0&&(c=n[0]._offset);for(var u,h=0,f=0,l=0,p=e.length;l=65536?(i-=65536,r+=String.fromCharCode(55296+(i>>>10),56320+(1023&i))):r+=String.fromCharCode(i)}else r+=String.fromCharCode((15&a)<<12|(63&t.getUint8(++s))<<6|(63&t.getUint8(++s))<<0);else r+=String.fromCharCode((31&a)<<6|63&t.getUint8(++s));else r+=String.fromCharCode(a)}return r}(this._view,this._offset,t);return this._offset+=t,e},mt.prototype._bin=function(t){var e=this._buffer.slice(this._offset,this._offset+t);return this._offset+=t,e},mt.prototype._parse=function(){var t,e=this._view.getUint8(this._offset++),n=0,r=0,i=0,s=0;if(e<192)return e<128?e:e<144?this._map(15&e):e<160?this._array(15&e):this._str(31&e);if(e>223)return-1*(255-e+1);switch(e){case 192:return null;case 194:return!1;case 195:return!0;case 196:return n=this._view.getUint8(this._offset),this._offset+=1,this._bin(n);case 197:return n=this._view.getUint16(this._offset),this._offset+=2,this._bin(n);case 198:return n=this._view.getUint32(this._offset),this._offset+=4,this._bin(n);case 199:return n=this._view.getUint8(this._offset),r=this._view.getInt8(this._offset+1),this._offset+=2,[r,this._bin(n)];case 200:return n=this._view.getUint16(this._offset),r=this._view.getInt8(this._offset+2),this._offset+=3,[r,this._bin(n)];case 201:return n=this._view.getUint32(this._offset),r=this._view.getInt8(this._offset+4),this._offset+=5,[r,this._bin(n)];case 202:return t=this._view.getFloat32(this._offset),this._offset+=4,t;case 203:return t=this._view.getFloat64(this._offset),this._offset+=8,t;case 204:return t=this._view.getUint8(this._offset),this._offset+=1,t;case 205:return t=this._view.getUint16(this._offset),this._offset+=2,t;case 206:return t=this._view.getUint32(this._offset),this._offset+=4,t;case 207:return i=this._view.getUint32(this._offset)*Math.pow(2,32),s=this._view.getUint32(this._offset+4),this._offset+=8,i+s;case 208:return t=this._view.getInt8(this._offset),this._offset+=1,t;case 209:return t=this._view.getInt16(this._offset),this._offset+=2,t;case 210:return t=this._view.getInt32(this._offset),this._offset+=4,t;case 211:return i=this._view.getInt32(this._offset)*Math.pow(2,32),s=this._view.getUint32(this._offset+4),this._offset+=8,i+s;case 212:return r=this._view.getInt8(this._offset),this._offset+=1,0===r?void(this._offset+=1):[r,this._bin(1)];case 213:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(2)];case 214:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(4)];case 215:return r=this._view.getInt8(this._offset),this._offset+=1,0===r?(i=this._view.getInt32(this._offset)*Math.pow(2,32),s=this._view.getUint32(this._offset+4),this._offset+=8,new Date(i+s)):[r,this._bin(8)];case 216:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(16)];case 217:return n=this._view.getUint8(this._offset),this._offset+=1,this._str(n);case 218:return n=this._view.getUint16(this._offset),this._offset+=2,this._str(n);case 219:return n=this._view.getUint32(this._offset),this._offset+=4,this._str(n);case 220:return n=this._view.getUint16(this._offset),this._offset+=2,this._array(n);case 221:return n=this._view.getUint32(this._offset),this._offset+=4,this._array(n);case 222:return n=this._view.getUint16(this._offset),this._offset+=2,this._map(n);case 223:return n=this._view.getUint32(this._offset),this._offset+=4,this._map(n)}throw new Error("Could not parse")};var _t=function(t){var e=new mt(t),n=e._parse();if(e._offset!==t.byteLength)throw new Error(t.byteLength-e._offset+" trailing bytes");return n};dt.encode=gt,dt.decode=_t;var bt,kt={exports:{}};!function(t){function e(t){if(t)return function(t){for(var n in e.prototype)t[n]=e.prototype[n];return t}(t)}t.exports=e,e.prototype.on=e.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},e.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i=Ct.CONNECT&&t.type<=Ct.CONNECT_ERROR))throw new Error("invalid packet type");if(!Tt(t.nsp))throw new Error("invalid namespace");if(!function(t){switch(t.type){case Ct.CONNECT:return void 0===t.data||St(t.data);case Ct.DISCONNECT:return void 0===t.data;case Ct.CONNECT_ERROR:return Tt(t.data)||St(t.data);default:return Array.isArray(t.data)}}(t))throw new Error("invalid payload");if(!(void 0===t.id||Rt(t.id)))throw new Error("invalid packet id")},Lt.prototype.destroy=function(){};var xt=pt.Encoder=At,Bt=pt.Decoder=Lt,Ut=Object.freeze(t({__proto__:null,default:pt,protocol:Et,get PacketType(){return bt},Encoder:xt,Decoder:Bt},[pt]));function jt(t,e,n){return t.on(e,n),function(){t.off(e,n)}}var Pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Nt=function(t){o(r,t);var e=d(r);function r(t,i,s){var o;return n(this,r),(o=e.call(this)).connected=!1,o.receiveBuffer=[],o.sendBuffer=[],o.ids=0,o.acks={},o.flags={},o.io=t,o.nsp=i,s&&s.auth&&(o.auth=s.auth),o.io._autoConnect&&o.open(),o}return i(r,[{key:"disconnected",get:function(){return!this.connected}},{key:"subEvents",value:function(){if(!this.subs){var t=this.io;this.subs=[jt(t,"open",this.onopen.bind(this)),jt(t,"packet",this.onpacket.bind(this)),jt(t,"error",this.onerror.bind(this)),jt(t,"close",this.onclose.bind(this))]}}},{key:"active",get:function(){return!!this.subs}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n1?e-1:0),r=1;r0&&t.jitter<=1?t.jitter:0,this.attempts=0}qt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},qt.prototype.reset=function(){this.attempts=0},qt.prototype.setMin=function(t){this.ms=t},qt.prototype.setMax=function(t){this.max=t},qt.prototype.setJitter=function(t){this.jitter=t};var Mt=function(t){o(s,t);var r=d(s);function s(t,i){var o,a;n(this,s),(o=r.call(this)).nsps={},o.subs=[],t&&"object"===e(t)&&(i=t,t=void 0),(i=i||{}).path=i.path||"/socket.io",o.opts=i,M(l(o),i),o.reconnection(!1!==i.reconnection),o.reconnectionAttempts(i.reconnectionAttempts||1/0),o.reconnectionDelay(i.reconnectionDelay||1e3),o.reconnectionDelayMax(i.reconnectionDelayMax||5e3),o.randomizationFactor(null!==(a=i.randomizationFactor)&&void 0!==a?a:.5),o.backoff=new qt({min:o.reconnectionDelay(),max:o.reconnectionDelayMax(),jitter:o.randomizationFactor()}),o.timeout(null==i.timeout?2e4:i.timeout),o._readyState="closed",o.uri=t;var c=i.parser||Ut;return o.encoder=new c.Encoder,o.decoder=new c.Decoder,o._autoConnect=!1!==i.autoConnect,o._autoConnect&&o.open(),o}return i(s,[{key:"reconnection",value:function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}},{key:"reconnectionAttempts",value:function(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}},{key:"reconnectionDelay",value:function(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}},{key:"randomizationFactor",value:function(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}},{key:"reconnectionDelayMax",value:function(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}},{key:"timeout",value:function(t){return arguments.length?(this._timeout=t,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(t){var e=this;if(~this._readyState.indexOf("open"))return this;this.engine=new lt(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var i=jt(n,"open",(function(){r.onopen(),t&&t()})),s=jt(n,"error",(function(n){r.cleanup(),r._readyState="closed",e.emitReserved("error",n),t?t(n):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var o=this._timeout;0===o&&i();var a=this.setTimeoutFn((function(){i(),n.close(),n.emit("error",new Error("timeout"))}),o);this.opts.autoUnref&&a.unref(),this.subs.push((function(){clearTimeout(a)}))}return this.subs.push(i),this.subs.push(s),this}},{key:"connect",value:function(t){return this.open(t)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",this.emitReserved("open");var t=this.engine;this.subs.push(jt(t,"ping",this.onping.bind(this)),jt(t,"data",this.ondata.bind(this)),jt(t,"error",this.onerror.bind(this)),jt(t,"close",this.onclose.bind(this)),jt(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){this.emitReserved("ping")}},{key:"ondata",value:function(t){this.decoder.add(t)}},{key:"ondecoded",value:function(t){this.emitReserved("packet",t)}},{key:"onerror",value:function(t){this.emitReserved("error",t)}},{key:"socket",value:function(t,e){var n=this.nsps[t];return n||(n=new Nt(this,t,e),this.nsps[t]=n),n}},{key:"_destroy",value:function(t){for(var e=0,n=Object.keys(this.nsps);e=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{var n=this.backoff.duration();this._reconnecting=!0;var r=this.setTimeoutFn((function(){e.skipReconnect||(t.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((function(n){n?(e._reconnecting=!1,e.reconnect(),t.emitReserved("reconnect_error",n)):e.onreconnect()})))}),n);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}},{key:"onreconnect",value:function(){var t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}]),s}(U),Dt={};function It(t,n){"object"===e(t)&&(n=t,t=void 0);var r,i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0,r=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),r=ft(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(t,(n=n||{}).path||"/socket.io"),s=i.source,o=i.id,a=i.path,c=Dt[o]&&a in Dt[o].nsps;return n.forceNew||n["force new connection"]||!1===n.multiplex||c?r=new Mt(s,n):(Dt[o]||(Dt[o]=new Mt(s,n)),r=Dt[o]),i.query&&!n.query&&(n.query=i.queryKey),r.socket(i.path,n)}return s(It,{Manager:Mt,Socket:Nt,io:It,connect:It}),It})); +//# sourceMappingURL=socket.io.msgpack.min.js.map diff --git a/node_modules/socket.io-client/dist/socket.io.msgpack.min.js.map b/node_modules/socket.io-client/dist/socket.io.msgpack.min.js.map new file mode 100644 index 0000000..6ce8058 --- /dev/null +++ b/node_modules/socket.io-client/dist/socket.io.msgpack.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socket.io.msgpack.min.js","sources":["../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/commons.js","../node_modules/@socket.io/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/encodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/decodePacket.browser.js","../node_modules/engine.io-client/node_modules/engine.io-parser/build/esm/index.js","../node_modules/@socket.io/component-emitter/index.mjs","../node_modules/engine.io-client/build/esm/globalThis.browser.js","../node_modules/engine.io-client/build/esm/util.js","../node_modules/engine.io-client/build/esm/contrib/yeast.js","../node_modules/engine.io-client/build/esm/transport.js","../node_modules/engine.io-client/build/esm/contrib/parseqs.js","../node_modules/engine.io-client/build/esm/contrib/has-cors.js","../node_modules/engine.io-client/build/esm/transports/xmlhttprequest.browser.js","../node_modules/engine.io-client/build/esm/transports/polling.js","../node_modules/engine.io-client/build/esm/transports/websocket-constructor.browser.js","../node_modules/engine.io-client/build/esm/transports/websocket.js","../node_modules/engine.io-client/build/esm/transports/index.js","../node_modules/engine.io-client/build/esm/contrib/parseuri.js","../node_modules/engine.io-client/build/esm/socket.js","../node_modules/notepack.io/browser/encode.js","../node_modules/notepack.io/browser/decode.js","../node_modules/notepack.io/lib/index.js","../node_modules/component-emitter/index.js","../node_modules/socket.io-msgpack-parser/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach(key => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = obj => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + content);\n };\n return fileReader.readAsDataURL(data);\n};\nexport default encodePacket;\n","import { ERROR_PACKET, PACKET_TYPES_REVERSE } from \"./commons.js\";\nimport { decode } from \"@socket.io/base64-arraybuffer\";\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n if (typeof encodedPacket !== \"string\") {\n return {\n type: \"message\",\n data: mapBinary(encodedPacket, binaryType)\n };\n }\n const type = encodedPacket.charAt(0);\n if (type === \"b\") {\n return {\n type: \"message\",\n data: decodeBase64Packet(encodedPacket.substring(1), binaryType)\n };\n }\n const packetType = PACKET_TYPES_REVERSE[type];\n if (!packetType) {\n return ERROR_PACKET;\n }\n return encodedPacket.length > 1\n ? {\n type: PACKET_TYPES_REVERSE[type],\n data: encodedPacket.substring(1)\n }\n : {\n type: PACKET_TYPES_REVERSE[type]\n };\n};\nconst decodeBase64Packet = (data, binaryType) => {\n if (withNativeArrayBuffer) {\n const decoded = decode(data);\n return mapBinary(decoded, binaryType);\n }\n else {\n return { base64: true, data }; // fallback for old browsers\n }\n};\nconst mapBinary = (data, binaryType) => {\n switch (binaryType) {\n case \"blob\":\n return data instanceof ArrayBuffer ? new Blob([data]) : data;\n case \"arraybuffer\":\n default:\n return data; // assuming the data is already an ArrayBuffer\n }\n};\nexport default decodePacket;\n","import encodePacket from \"./encodePacket.js\";\nimport decodePacket from \"./decodePacket.js\";\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n // some packets may be added to the array while encoding, so the initial length must be saved\n const length = packets.length;\n const encodedPackets = new Array(length);\n let count = 0;\n packets.forEach((packet, i) => {\n // force base64 encoding for binary packets\n encodePacket(packet, false, encodedPacket => {\n encodedPackets[i] = encodedPacket;\n if (++count === length) {\n callback(encodedPackets.join(SEPARATOR));\n }\n });\n });\n};\nconst decodePayload = (encodedPayload, binaryType) => {\n const encodedPackets = encodedPayload.split(SEPARATOR);\n const packets = [];\n for (let i = 0; i < encodedPackets.length; i++) {\n const decodedPacket = decodePacket(encodedPackets[i], binaryType);\n packets.push(decodedPacket);\n if (decodedPacket.type === \"error\") {\n break;\n }\n }\n return packets;\n};\nexport const protocol = 4;\nexport { encodePacket, encodePayload, decodePacket, decodePayload };\n","/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nexport function Emitter(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n function on() {\n this.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks['$' + event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks['$' + event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n\n // Remove event specific arrays for event types that no\n // one is subscribed for to avoid memory leak.\n if (callbacks.length === 0) {\n delete this._callbacks['$' + event];\n }\n\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n\n var args = new Array(arguments.length - 1)\n , callbacks = this._callbacks['$' + event];\n\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","export default (() => {\n if (typeof self !== \"undefined\") {\n return self;\n }\n else if (typeof window !== \"undefined\") {\n return window;\n }\n else {\n return Function(\"return this\")();\n }\n})();\n","import globalThis from \"./globalThis.js\";\nexport function pick(obj, ...attr) {\n return attr.reduce((acc, k) => {\n if (obj.hasOwnProperty(k)) {\n acc[k] = obj[k];\n }\n return acc;\n }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = clearTimeout;\nexport function installTimerFunctions(obj, opts) {\n if (opts.useNativeTimers) {\n obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);\n obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);\n }\n else {\n obj.setTimeoutFn = setTimeout.bind(globalThis);\n obj.clearTimeoutFn = clearTimeout.bind(globalThis);\n }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nexport function byteLength(obj) {\n if (typeof obj === \"string\") {\n return utf8Length(obj);\n }\n // arraybuffer or blob\n return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n let c = 0, length = 0;\n for (let i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n","// imported from https://github.com/unshiftio/yeast\n'use strict';\nconst alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};\nlet seed = 0, i = 0, prev;\n/**\n * Return a string representing the specified number.\n *\n * @param {Number} num The number to convert.\n * @returns {String} The string representation of the number.\n * @api public\n */\nexport function encode(num) {\n let encoded = '';\n do {\n encoded = alphabet[num % length] + encoded;\n num = Math.floor(num / length);\n } while (num > 0);\n return encoded;\n}\n/**\n * Return the integer value specified by the given string.\n *\n * @param {String} str The string to convert.\n * @returns {Number} The integer value represented by the string.\n * @api public\n */\nexport function decode(str) {\n let decoded = 0;\n for (i = 0; i < str.length; i++) {\n decoded = decoded * length + map[str.charAt(i)];\n }\n return decoded;\n}\n/**\n * Yeast: A tiny growing id generator.\n *\n * @returns {String} A unique id.\n * @api public\n */\nexport function yeast() {\n const now = encode(+new Date());\n if (now !== prev)\n return seed = 0, prev = now;\n return now + '.' + encode(seed++);\n}\n//\n// Map each character to its index.\n//\nfor (; i < length; i++)\n map[alphabet[i]] = i;\n","import { decodePacket } from \"engine.io-parser\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions } from \"./util.js\";\nclass TransportError extends Error {\n constructor(reason, description, context) {\n super(reason);\n this.description = description;\n this.context = context;\n this.type = \"TransportError\";\n }\n}\nexport class Transport extends Emitter {\n /**\n * Transport abstract constructor.\n *\n * @param {Object} options.\n * @api private\n */\n constructor(opts) {\n super();\n this.writable = false;\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.query = opts.query;\n this.readyState = \"\";\n this.socket = opts.socket;\n }\n /**\n * Emits an error.\n *\n * @param {String} reason\n * @param description\n * @param context - the error context\n * @return {Transport} for chaining\n * @api protected\n */\n onError(reason, description, context) {\n super.emitReserved(\"error\", new TransportError(reason, description, context));\n return this;\n }\n /**\n * Opens the transport.\n *\n * @api public\n */\n open() {\n if (\"closed\" === this.readyState || \"\" === this.readyState) {\n this.readyState = \"opening\";\n this.doOpen();\n }\n return this;\n }\n /**\n * Closes the transport.\n *\n * @api public\n */\n close() {\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.doClose();\n this.onClose();\n }\n return this;\n }\n /**\n * Sends multiple packets.\n *\n * @param {Array} packets\n * @api public\n */\n send(packets) {\n if (\"open\" === this.readyState) {\n this.write(packets);\n }\n else {\n // this might happen if the transport was silently closed in the beforeunload event handler\n }\n }\n /**\n * Called upon open\n *\n * @api protected\n */\n onOpen() {\n this.readyState = \"open\";\n this.writable = true;\n super.emitReserved(\"open\");\n }\n /**\n * Called with data.\n *\n * @param {String} data\n * @api protected\n */\n onData(data) {\n const packet = decodePacket(data, this.socket.binaryType);\n this.onPacket(packet);\n }\n /**\n * Called with a decoded packet.\n *\n * @api protected\n */\n onPacket(packet) {\n super.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon close.\n *\n * @api protected\n */\n onClose(details) {\n this.readyState = \"closed\";\n super.emitReserved(\"close\", details);\n }\n}\n","// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nexport function encode(obj) {\n let str = '';\n for (let i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (str.length)\n str += '&';\n str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n }\n }\n return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nexport function decode(qs) {\n let qry = {};\n let pairs = qs.split('&');\n for (let i = 0, l = pairs.length; i < l; i++) {\n let pair = pairs[i].split('=');\n qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n return qry;\n}\n","// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n value = typeof XMLHttpRequest !== 'undefined' &&\n 'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n // if XMLHttp support is disabled in IE then it will throw\n // when trying to create\n}\nexport const hasCORS = value;\n","// browser shim for xmlhttprequest module\nimport { hasCORS } from \"../contrib/has-cors.js\";\nimport globalThis from \"../globalThis.js\";\nexport default function (opts) {\n const xdomain = opts.xdomain;\n // XMLHttpRequest can be disabled on IE\n try {\n if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {\n return new XMLHttpRequest();\n }\n }\n catch (e) { }\n if (!xdomain) {\n try {\n return new globalThis[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n }\n catch (e) { }\n }\n}\n","import { Transport } from \"../transport.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { encodePayload, decodePayload } from \"engine.io-parser\";\nimport XMLHttpRequest from \"./xmlhttprequest.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { installTimerFunctions, pick } from \"../util.js\";\nimport globalThis from \"../globalThis.js\";\nfunction empty() { }\nconst hasXHR2 = (function () {\n const xhr = new XMLHttpRequest({\n xdomain: false\n });\n return null != xhr.responseType;\n})();\nexport class Polling extends Transport {\n /**\n * XHR Polling constructor.\n *\n * @param {Object} opts\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.polling = false;\n if (typeof location !== \"undefined\") {\n const isSSL = \"https:\" === location.protocol;\n let port = location.port;\n // some user agents have empty `location.port`\n if (!port) {\n port = isSSL ? \"443\" : \"80\";\n }\n this.xd =\n (typeof location !== \"undefined\" &&\n opts.hostname !== location.hostname) ||\n port !== opts.port;\n this.xs = opts.secure !== isSSL;\n }\n /**\n * XHR supports binary\n */\n const forceBase64 = opts && opts.forceBase64;\n this.supportsBinary = hasXHR2 && !forceBase64;\n }\n /**\n * Transport name.\n */\n get name() {\n return \"polling\";\n }\n /**\n * Opens the socket (triggers polling). We write a PING message to determine\n * when the transport is open.\n *\n * @api private\n */\n doOpen() {\n this.poll();\n }\n /**\n * Pauses polling.\n *\n * @param {Function} callback upon buffers are flushed and transport is paused\n * @api private\n */\n pause(onPause) {\n this.readyState = \"pausing\";\n const pause = () => {\n this.readyState = \"paused\";\n onPause();\n };\n if (this.polling || !this.writable) {\n let total = 0;\n if (this.polling) {\n total++;\n this.once(\"pollComplete\", function () {\n --total || pause();\n });\n }\n if (!this.writable) {\n total++;\n this.once(\"drain\", function () {\n --total || pause();\n });\n }\n }\n else {\n pause();\n }\n }\n /**\n * Starts polling cycle.\n *\n * @api public\n */\n poll() {\n this.polling = true;\n this.doPoll();\n this.emitReserved(\"poll\");\n }\n /**\n * Overloads onData to detect payloads.\n *\n * @api private\n */\n onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n else {\n }\n }\n }\n /**\n * For polling, send a close packet.\n *\n * @api private\n */\n doClose() {\n const close = () => {\n this.write([{ type: \"close\" }]);\n };\n if (\"open\" === this.readyState) {\n close();\n }\n else {\n // in case we're trying to close while\n // handshaking is in progress (GH-164)\n this.once(\"open\", close);\n }\n }\n /**\n * Writes a packets payload.\n *\n * @param {Array} data packets\n * @param {Function} drain callback\n * @api private\n */\n write(packets) {\n this.writable = false;\n encodePayload(packets, data => {\n this.doWrite(data, () => {\n this.writable = true;\n this.emitReserved(\"drain\");\n });\n });\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"https\" : \"http\";\n let port = \"\";\n // cache busting is forced\n if (false !== this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n if (!this.supportsBinary && !query.sid) {\n query.b64 = 1;\n }\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"https\" === schema && Number(this.opts.port) !== 443) ||\n (\"http\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Creates a request.\n *\n * @param {String} method\n * @api private\n */\n request(opts = {}) {\n Object.assign(opts, { xd: this.xd, xs: this.xs }, this.opts);\n return new Request(this.uri(), opts);\n }\n /**\n * Sends data.\n *\n * @param {String} data to send.\n * @param {Function} called upon flush.\n * @api private\n */\n doWrite(data, fn) {\n const req = this.request({\n method: \"POST\",\n data: data\n });\n req.on(\"success\", fn);\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr post error\", xhrStatus, context);\n });\n }\n /**\n * Starts a poll cycle.\n *\n * @api private\n */\n doPoll() {\n const req = this.request();\n req.on(\"data\", this.onData.bind(this));\n req.on(\"error\", (xhrStatus, context) => {\n this.onError(\"xhr poll error\", xhrStatus, context);\n });\n this.pollXhr = req;\n }\n}\nexport class Request extends Emitter {\n /**\n * Request constructor\n *\n * @param {Object} options\n * @api public\n */\n constructor(uri, opts) {\n super();\n installTimerFunctions(this, opts);\n this.opts = opts;\n this.method = opts.method || \"GET\";\n this.uri = uri;\n this.async = false !== opts.async;\n this.data = undefined !== opts.data ? opts.data : null;\n this.create();\n }\n /**\n * Creates the XHR object and sends the request.\n *\n * @api private\n */\n create() {\n const opts = pick(this.opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n opts.xdomain = !!this.opts.xd;\n opts.xscheme = !!this.opts.xs;\n const xhr = (this.xhr = new XMLHttpRequest(opts));\n try {\n xhr.open(this.method, this.uri, this.async);\n try {\n if (this.opts.extraHeaders) {\n xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n for (let i in this.opts.extraHeaders) {\n if (this.opts.extraHeaders.hasOwnProperty(i)) {\n xhr.setRequestHeader(i, this.opts.extraHeaders[i]);\n }\n }\n }\n }\n catch (e) { }\n if (\"POST\" === this.method) {\n try {\n xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n }\n catch (e) { }\n }\n try {\n xhr.setRequestHeader(\"Accept\", \"*/*\");\n }\n catch (e) { }\n // ie6 check\n if (\"withCredentials\" in xhr) {\n xhr.withCredentials = this.opts.withCredentials;\n }\n if (this.opts.requestTimeout) {\n xhr.timeout = this.opts.requestTimeout;\n }\n xhr.onreadystatechange = () => {\n if (4 !== xhr.readyState)\n return;\n if (200 === xhr.status || 1223 === xhr.status) {\n this.onLoad();\n }\n else {\n // make sure the `error` event handler that's user-set\n // does not throw in the same tick and gets caught here\n this.setTimeoutFn(() => {\n this.onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n }, 0);\n }\n };\n xhr.send(this.data);\n }\n catch (e) {\n // Need to defer since .create() is called directly from the constructor\n // and thus the 'error' event can only be only bound *after* this exception\n // occurs. Therefore, also, we cannot throw here at all.\n this.setTimeoutFn(() => {\n this.onError(e);\n }, 0);\n return;\n }\n if (typeof document !== \"undefined\") {\n this.index = Request.requestsCount++;\n Request.requests[this.index] = this;\n }\n }\n /**\n * Called upon error.\n *\n * @api private\n */\n onError(err) {\n this.emitReserved(\"error\", err, this.xhr);\n this.cleanup(true);\n }\n /**\n * Cleans up house.\n *\n * @api private\n */\n cleanup(fromError) {\n if (\"undefined\" === typeof this.xhr || null === this.xhr) {\n return;\n }\n this.xhr.onreadystatechange = empty;\n if (fromError) {\n try {\n this.xhr.abort();\n }\n catch (e) { }\n }\n if (typeof document !== \"undefined\") {\n delete Request.requests[this.index];\n }\n this.xhr = null;\n }\n /**\n * Called upon load.\n *\n * @api private\n */\n onLoad() {\n const data = this.xhr.responseText;\n if (data !== null) {\n this.emitReserved(\"data\", data);\n this.emitReserved(\"success\");\n this.cleanup();\n }\n }\n /**\n * Aborts the request.\n *\n * @api public\n */\n abort() {\n this.cleanup();\n }\n}\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n // @ts-ignore\n if (typeof attachEvent === \"function\") {\n // @ts-ignore\n attachEvent(\"onunload\", unloadHandler);\n }\n else if (typeof addEventListener === \"function\") {\n const terminationEvent = \"onpagehide\" in globalThis ? \"pagehide\" : \"unload\";\n addEventListener(terminationEvent, unloadHandler, false);\n }\n}\nfunction unloadHandler() {\n for (let i in Request.requests) {\n if (Request.requests.hasOwnProperty(i)) {\n Request.requests[i].abort();\n }\n }\n}\n","import globalThis from \"../globalThis.js\";\nexport const nextTick = (() => {\n const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n if (isPromiseAvailable) {\n return cb => Promise.resolve().then(cb);\n }\n else {\n return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n }\n})();\nexport const WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;\nexport const usingBrowserWebSocket = true;\nexport const defaultBinaryType = \"arraybuffer\";\n","import { Transport } from \"../transport.js\";\nimport { encode } from \"../contrib/parseqs.js\";\nimport { yeast } from \"../contrib/yeast.js\";\nimport { pick } from \"../util.js\";\nimport { defaultBinaryType, nextTick, usingBrowserWebSocket, WebSocket } from \"./websocket-constructor.js\";\nimport { encodePacket } from \"engine.io-parser\";\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n typeof navigator.product === \"string\" &&\n navigator.product.toLowerCase() === \"reactnative\";\nexport class WS extends Transport {\n /**\n * WebSocket transport constructor.\n *\n * @api {Object} connection options\n * @api public\n */\n constructor(opts) {\n super(opts);\n this.supportsBinary = !opts.forceBase64;\n }\n /**\n * Transport name.\n *\n * @api public\n */\n get name() {\n return \"websocket\";\n }\n /**\n * Opens socket.\n *\n * @api private\n */\n doOpen() {\n if (!this.check()) {\n // let probe timeout\n return;\n }\n const uri = this.uri();\n const protocols = this.opts.protocols;\n // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n const opts = isReactNative\n ? {}\n : pick(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n if (this.opts.extraHeaders) {\n opts.headers = this.opts.extraHeaders;\n }\n try {\n this.ws =\n usingBrowserWebSocket && !isReactNative\n ? protocols\n ? new WebSocket(uri, protocols)\n : new WebSocket(uri)\n : new WebSocket(uri, protocols, opts);\n }\n catch (err) {\n return this.emitReserved(\"error\", err);\n }\n this.ws.binaryType = this.socket.binaryType || defaultBinaryType;\n this.addEventListeners();\n }\n /**\n * Adds event listeners to the socket\n *\n * @api private\n */\n addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = closeEvent => this.onClose({\n description: \"websocket connection closed\",\n context: closeEvent\n });\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }\n /**\n * Writes data to socket.\n *\n * @param {Array} array of packets.\n * @api private\n */\n write(packets) {\n this.writable = false;\n // encodePacket efficient as it uses WS framing\n // no need for encodePayload\n for (let i = 0; i < packets.length; i++) {\n const packet = packets[i];\n const lastPacket = i === packets.length - 1;\n encodePacket(packet, this.supportsBinary, data => {\n // always create a new object (GH-437)\n const opts = {};\n if (!usingBrowserWebSocket) {\n if (packet.options) {\n opts.compress = packet.options.compress;\n }\n if (this.opts.perMessageDeflate) {\n const len = \n // @ts-ignore\n \"string\" === typeof data ? Buffer.byteLength(data) : data.length;\n if (len < this.opts.perMessageDeflate.threshold) {\n opts.compress = false;\n }\n }\n }\n // Sometimes the websocket has already been closed but the browser didn't\n // have a chance of informing us about it yet, in that case send will\n // throw an error\n try {\n if (usingBrowserWebSocket) {\n // TypeError is thrown when passing the second argument on Safari\n this.ws.send(data);\n }\n else {\n this.ws.send(data, opts);\n }\n }\n catch (e) {\n }\n if (lastPacket) {\n // fake drain\n // defer to next tick to allow Socket to clear writeBuffer\n nextTick(() => {\n this.writable = true;\n this.emitReserved(\"drain\");\n }, this.setTimeoutFn);\n }\n });\n }\n }\n /**\n * Closes socket.\n *\n * @api private\n */\n doClose() {\n if (typeof this.ws !== \"undefined\") {\n this.ws.close();\n this.ws = null;\n }\n }\n /**\n * Generates uri for connection.\n *\n * @api private\n */\n uri() {\n let query = this.query || {};\n const schema = this.opts.secure ? \"wss\" : \"ws\";\n let port = \"\";\n // avoid port if default for schema\n if (this.opts.port &&\n ((\"wss\" === schema && Number(this.opts.port) !== 443) ||\n (\"ws\" === schema && Number(this.opts.port) !== 80))) {\n port = \":\" + this.opts.port;\n }\n // append timestamp to URI\n if (this.opts.timestampRequests) {\n query[this.opts.timestampParam] = yeast();\n }\n // communicate binary support capabilities\n if (!this.supportsBinary) {\n query.b64 = 1;\n }\n const encodedQuery = encode(query);\n const ipv6 = this.opts.hostname.indexOf(\":\") !== -1;\n return (schema +\n \"://\" +\n (ipv6 ? \"[\" + this.opts.hostname + \"]\" : this.opts.hostname) +\n port +\n this.opts.path +\n (encodedQuery.length ? \"?\" + encodedQuery : \"\"));\n }\n /**\n * Feature detection for WebSocket.\n *\n * @return {Boolean} whether this transport is available.\n * @api public\n */\n check() {\n return (!!WebSocket &&\n !(\"__initialize\" in WebSocket && this.name === WS.prototype.name));\n }\n}\n","import { Polling } from \"./polling.js\";\nimport { WS } from \"./websocket.js\";\nexport const transports = {\n websocket: WS,\n polling: Polling\n};\n","// imported from https://github.com/galkn/parseuri\n/**\n * Parses an URI\n *\n * @author Steven Levithan (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nexport function parse(str) {\n const src = str, b = str.indexOf('['), e = str.indexOf(']');\n if (b != -1 && e != -1) {\n str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n }\n let m = re.exec(str || ''), uri = {}, i = 14;\n while (i--) {\n uri[parts[i]] = m[i] || '';\n }\n if (b != -1 && e != -1) {\n uri.source = src;\n uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n uri.ipv6uri = true;\n }\n uri.pathNames = pathNames(uri, uri['path']);\n uri.queryKey = queryKey(uri, uri['query']);\n return uri;\n}\nfunction pathNames(obj, path) {\n const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n if (path.substr(0, 1) == '/' || path.length === 0) {\n names.splice(0, 1);\n }\n if (path.substr(path.length - 1, 1) == '/') {\n names.splice(names.length - 1, 1);\n }\n return names;\n}\nfunction queryKey(uri, query) {\n const data = {};\n query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n if ($1) {\n data[$1] = $2;\n }\n });\n return data;\n}\n","import { transports } from \"./transports/index.js\";\nimport { installTimerFunctions, byteLength } from \"./util.js\";\nimport { decode } from \"./contrib/parseqs.js\";\nimport { parse } from \"./contrib/parseuri.js\";\nimport { Emitter } from \"@socket.io/component-emitter\";\nimport { protocol } from \"engine.io-parser\";\nexport class Socket extends Emitter {\n /**\n * Socket constructor.\n *\n * @param {String|Object} uri or options\n * @param {Object} opts - options\n * @api public\n */\n constructor(uri, opts = {}) {\n super();\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = null;\n }\n if (uri) {\n uri = parse(uri);\n opts.hostname = uri.host;\n opts.secure = uri.protocol === \"https\" || uri.protocol === \"wss\";\n opts.port = uri.port;\n if (uri.query)\n opts.query = uri.query;\n }\n else if (opts.host) {\n opts.hostname = parse(opts.host).host;\n }\n installTimerFunctions(this, opts);\n this.secure =\n null != opts.secure\n ? opts.secure\n : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n if (opts.hostname && !opts.port) {\n // if no port is specified manually, use the protocol default\n opts.port = this.secure ? \"443\" : \"80\";\n }\n this.hostname =\n opts.hostname ||\n (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n this.port =\n opts.port ||\n (typeof location !== \"undefined\" && location.port\n ? location.port\n : this.secure\n ? \"443\"\n : \"80\");\n this.transports = opts.transports || [\"polling\", \"websocket\"];\n this.readyState = \"\";\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n this.opts = Object.assign({\n path: \"/engine.io\",\n agent: false,\n withCredentials: false,\n upgrade: true,\n timestampParam: \"t\",\n rememberUpgrade: false,\n rejectUnauthorized: true,\n perMessageDeflate: {\n threshold: 1024\n },\n transportOptions: {},\n closeOnBeforeunload: true\n }, opts);\n this.opts.path = this.opts.path.replace(/\\/$/, \"\") + \"/\";\n if (typeof this.opts.query === \"string\") {\n this.opts.query = decode(this.opts.query);\n }\n // set on handshake\n this.id = null;\n this.upgrades = null;\n this.pingInterval = null;\n this.pingTimeout = null;\n // set on heartbeat\n this.pingTimeoutTimer = null;\n if (typeof addEventListener === \"function\") {\n if (this.opts.closeOnBeforeunload) {\n // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n // closed/reloaded)\n addEventListener(\"beforeunload\", () => {\n if (this.transport) {\n // silently close the transport\n this.transport.removeAllListeners();\n this.transport.close();\n }\n }, false);\n }\n if (this.hostname !== \"localhost\") {\n this.offlineEventListener = () => {\n this.onClose(\"transport close\", {\n description: \"network connection lost\"\n });\n };\n addEventListener(\"offline\", this.offlineEventListener, false);\n }\n }\n this.open();\n }\n /**\n * Creates transport of the given type.\n *\n * @param {String} transport name\n * @return {Transport}\n * @api private\n */\n createTransport(name) {\n const query = Object.assign({}, this.opts.query);\n // append engine.io protocol identifier\n query.EIO = protocol;\n // transport name\n query.transport = name;\n // session id if we already have one\n if (this.id)\n query.sid = this.id;\n const opts = Object.assign({}, this.opts.transportOptions[name], this.opts, {\n query,\n socket: this,\n hostname: this.hostname,\n secure: this.secure,\n port: this.port\n });\n return new transports[name](opts);\n }\n /**\n * Initializes transport to use and starts probe.\n *\n * @api private\n */\n open() {\n let transport;\n if (this.opts.rememberUpgrade &&\n Socket.priorWebsocketSuccess &&\n this.transports.indexOf(\"websocket\") !== -1) {\n transport = \"websocket\";\n }\n else if (0 === this.transports.length) {\n // Emit error on next tick so it can be listened to\n this.setTimeoutFn(() => {\n this.emitReserved(\"error\", \"No transports available\");\n }, 0);\n return;\n }\n else {\n transport = this.transports[0];\n }\n this.readyState = \"opening\";\n // Retry with the next transport if the transport is disabled (jsonp: false)\n try {\n transport = this.createTransport(transport);\n }\n catch (e) {\n this.transports.shift();\n this.open();\n return;\n }\n transport.open();\n this.setTransport(transport);\n }\n /**\n * Sets the current transport. Disables the existing one (if any).\n *\n * @api private\n */\n setTransport(transport) {\n if (this.transport) {\n this.transport.removeAllListeners();\n }\n // set up transport\n this.transport = transport;\n // set up transport listeners\n transport\n .on(\"drain\", this.onDrain.bind(this))\n .on(\"packet\", this.onPacket.bind(this))\n .on(\"error\", this.onError.bind(this))\n .on(\"close\", reason => this.onClose(\"transport close\", reason));\n }\n /**\n * Probes a transport.\n *\n * @param {String} transport name\n * @api private\n */\n probe(name) {\n let transport = this.createTransport(name);\n let failed = false;\n Socket.priorWebsocketSuccess = false;\n const onTransportOpen = () => {\n if (failed)\n return;\n transport.send([{ type: \"ping\", data: \"probe\" }]);\n transport.once(\"packet\", msg => {\n if (failed)\n return;\n if (\"pong\" === msg.type && \"probe\" === msg.data) {\n this.upgrading = true;\n this.emitReserved(\"upgrading\", transport);\n if (!transport)\n return;\n Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n this.transport.pause(() => {\n if (failed)\n return;\n if (\"closed\" === this.readyState)\n return;\n cleanup();\n this.setTransport(transport);\n transport.send([{ type: \"upgrade\" }]);\n this.emitReserved(\"upgrade\", transport);\n transport = null;\n this.upgrading = false;\n this.flush();\n });\n }\n else {\n const err = new Error(\"probe error\");\n // @ts-ignore\n err.transport = transport.name;\n this.emitReserved(\"upgradeError\", err);\n }\n });\n };\n function freezeTransport() {\n if (failed)\n return;\n // Any callback called by transport should be ignored since now\n failed = true;\n cleanup();\n transport.close();\n transport = null;\n }\n // Handle any error that happens while probing\n const onerror = err => {\n const error = new Error(\"probe error: \" + err);\n // @ts-ignore\n error.transport = transport.name;\n freezeTransport();\n this.emitReserved(\"upgradeError\", error);\n };\n function onTransportClose() {\n onerror(\"transport closed\");\n }\n // When the socket is closed while we're probing\n function onclose() {\n onerror(\"socket closed\");\n }\n // When the socket is upgraded while we're probing\n function onupgrade(to) {\n if (transport && to.name !== transport.name) {\n freezeTransport();\n }\n }\n // Remove all listeners on the transport and on self\n const cleanup = () => {\n transport.removeListener(\"open\", onTransportOpen);\n transport.removeListener(\"error\", onerror);\n transport.removeListener(\"close\", onTransportClose);\n this.off(\"close\", onclose);\n this.off(\"upgrading\", onupgrade);\n };\n transport.once(\"open\", onTransportOpen);\n transport.once(\"error\", onerror);\n transport.once(\"close\", onTransportClose);\n this.once(\"close\", onclose);\n this.once(\"upgrading\", onupgrade);\n transport.open();\n }\n /**\n * Called when connection is deemed open.\n *\n * @api private\n */\n onOpen() {\n this.readyState = \"open\";\n Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n this.emitReserved(\"open\");\n this.flush();\n // we check for `readyState` in case an `open`\n // listener already closed the socket\n if (\"open\" === this.readyState &&\n this.opts.upgrade &&\n this.transport.pause) {\n let i = 0;\n const l = this.upgrades.length;\n for (; i < l; i++) {\n this.probe(this.upgrades[i]);\n }\n }\n }\n /**\n * Handles a packet.\n *\n * @api private\n */\n onPacket(packet) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n this.emitReserved(\"packet\", packet);\n // Socket is live - any packet counts\n this.emitReserved(\"heartbeat\");\n switch (packet.type) {\n case \"open\":\n this.onHandshake(JSON.parse(packet.data));\n break;\n case \"ping\":\n this.resetPingTimeout();\n this.sendPacket(\"pong\");\n this.emitReserved(\"ping\");\n this.emitReserved(\"pong\");\n break;\n case \"error\":\n const err = new Error(\"server error\");\n // @ts-ignore\n err.code = packet.data;\n this.onError(err);\n break;\n case \"message\":\n this.emitReserved(\"data\", packet.data);\n this.emitReserved(\"message\", packet.data);\n break;\n }\n }\n else {\n }\n }\n /**\n * Called upon handshake completion.\n *\n * @param {Object} data - handshake obj\n * @api private\n */\n onHandshake(data) {\n this.emitReserved(\"handshake\", data);\n this.id = data.sid;\n this.transport.query.sid = data.sid;\n this.upgrades = this.filterUpgrades(data.upgrades);\n this.pingInterval = data.pingInterval;\n this.pingTimeout = data.pingTimeout;\n this.maxPayload = data.maxPayload;\n this.onOpen();\n // In case open handler closes socket\n if (\"closed\" === this.readyState)\n return;\n this.resetPingTimeout();\n }\n /**\n * Sets and resets ping timeout timer based on server pings.\n *\n * @api private\n */\n resetPingTimeout() {\n this.clearTimeoutFn(this.pingTimeoutTimer);\n this.pingTimeoutTimer = this.setTimeoutFn(() => {\n this.onClose(\"ping timeout\");\n }, this.pingInterval + this.pingTimeout);\n if (this.opts.autoUnref) {\n this.pingTimeoutTimer.unref();\n }\n }\n /**\n * Called on `drain` event\n *\n * @api private\n */\n onDrain() {\n this.writeBuffer.splice(0, this.prevBufferLen);\n // setting prevBufferLen = 0 is very important\n // for example, when upgrading, upgrade packet is sent over,\n // and a nonzero prevBufferLen could cause problems on `drain`\n this.prevBufferLen = 0;\n if (0 === this.writeBuffer.length) {\n this.emitReserved(\"drain\");\n }\n else {\n this.flush();\n }\n }\n /**\n * Flush write buffers.\n *\n * @api private\n */\n flush() {\n if (\"closed\" !== this.readyState &&\n this.transport.writable &&\n !this.upgrading &&\n this.writeBuffer.length) {\n const packets = this.getWritablePackets();\n this.transport.send(packets);\n // keep track of current length of writeBuffer\n // splice writeBuffer and callbackBuffer on `drain`\n this.prevBufferLen = packets.length;\n this.emitReserved(\"flush\");\n }\n }\n /**\n * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n * long-polling)\n *\n * @private\n */\n getWritablePackets() {\n const shouldCheckPayloadSize = this.maxPayload &&\n this.transport.name === \"polling\" &&\n this.writeBuffer.length > 1;\n if (!shouldCheckPayloadSize) {\n return this.writeBuffer;\n }\n let payloadSize = 1; // first packet type\n for (let i = 0; i < this.writeBuffer.length; i++) {\n const data = this.writeBuffer[i].data;\n if (data) {\n payloadSize += byteLength(data);\n }\n if (i > 0 && payloadSize > this.maxPayload) {\n return this.writeBuffer.slice(0, i);\n }\n payloadSize += 2; // separator + packet type\n }\n return this.writeBuffer;\n }\n /**\n * Sends a message.\n *\n * @param {String} message.\n * @param {Function} callback function.\n * @param {Object} options.\n * @return {Socket} for chaining.\n * @api public\n */\n write(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n send(msg, options, fn) {\n this.sendPacket(\"message\", msg, options, fn);\n return this;\n }\n /**\n * Sends a packet.\n *\n * @param {String} packet type.\n * @param {String} data.\n * @param {Object} options.\n * @param {Function} callback function.\n * @api private\n */\n sendPacket(type, data, options, fn) {\n if (\"function\" === typeof data) {\n fn = data;\n data = undefined;\n }\n if (\"function\" === typeof options) {\n fn = options;\n options = null;\n }\n if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n return;\n }\n options = options || {};\n options.compress = false !== options.compress;\n const packet = {\n type: type,\n data: data,\n options: options\n };\n this.emitReserved(\"packetCreate\", packet);\n this.writeBuffer.push(packet);\n if (fn)\n this.once(\"flush\", fn);\n this.flush();\n }\n /**\n * Closes the connection.\n *\n * @api public\n */\n close() {\n const close = () => {\n this.onClose(\"forced close\");\n this.transport.close();\n };\n const cleanupAndClose = () => {\n this.off(\"upgrade\", cleanupAndClose);\n this.off(\"upgradeError\", cleanupAndClose);\n close();\n };\n const waitForUpgrade = () => {\n // wait for upgrade to finish since we can't send packets while pausing a transport\n this.once(\"upgrade\", cleanupAndClose);\n this.once(\"upgradeError\", cleanupAndClose);\n };\n if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n this.readyState = \"closing\";\n if (this.writeBuffer.length) {\n this.once(\"drain\", () => {\n if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n });\n }\n else if (this.upgrading) {\n waitForUpgrade();\n }\n else {\n close();\n }\n }\n return this;\n }\n /**\n * Called upon transport error\n *\n * @api private\n */\n onError(err) {\n Socket.priorWebsocketSuccess = false;\n this.emitReserved(\"error\", err);\n this.onClose(\"transport error\", err);\n }\n /**\n * Called upon transport close.\n *\n * @api private\n */\n onClose(reason, description) {\n if (\"opening\" === this.readyState ||\n \"open\" === this.readyState ||\n \"closing\" === this.readyState) {\n // clear timers\n this.clearTimeoutFn(this.pingTimeoutTimer);\n // stop event from firing again for transport\n this.transport.removeAllListeners(\"close\");\n // ensure transport won't stay open\n this.transport.close();\n // ignore further transport communication\n this.transport.removeAllListeners();\n if (typeof removeEventListener === \"function\") {\n removeEventListener(\"offline\", this.offlineEventListener, false);\n }\n // set ready state\n this.readyState = \"closed\";\n // clear session id\n this.id = null;\n // emit close event\n this.emitReserved(\"close\", reason, description);\n // clean buffers after, so users can still\n // grab the buffers on `close` event\n this.writeBuffer = [];\n this.prevBufferLen = 0;\n }\n }\n /**\n * Filters upgrades, returning only those matching client transports.\n *\n * @param {Array} server upgrades\n * @api private\n *\n */\n filterUpgrades(upgrades) {\n const filteredUpgrades = [];\n let i = 0;\n const j = upgrades.length;\n for (; i < j; i++) {\n if (~this.transports.indexOf(upgrades[i]))\n filteredUpgrades.push(upgrades[i]);\n }\n return filteredUpgrades;\n }\n}\nSocket.protocol = protocol;\n","'use strict';\n\nfunction utf8Write(view, offset, str) {\n var c = 0;\n for (var i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n view.setUint8(offset++, c);\n }\n else if (c < 0x800) {\n view.setUint8(offset++, 0xc0 | (c >> 6));\n view.setUint8(offset++, 0x80 | (c & 0x3f));\n }\n else if (c < 0xd800 || c >= 0xe000) {\n view.setUint8(offset++, 0xe0 | (c >> 12));\n view.setUint8(offset++, 0x80 | (c >> 6) & 0x3f);\n view.setUint8(offset++, 0x80 | (c & 0x3f));\n }\n else {\n i++;\n c = 0x10000 + (((c & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));\n view.setUint8(offset++, 0xf0 | (c >> 18));\n view.setUint8(offset++, 0x80 | (c >> 12) & 0x3f);\n view.setUint8(offset++, 0x80 | (c >> 6) & 0x3f);\n view.setUint8(offset++, 0x80 | (c & 0x3f));\n }\n }\n}\n\nfunction utf8Length(str) {\n var c = 0, length = 0;\n for (var i = 0, l = str.length; i < l; i++) {\n c = str.charCodeAt(i);\n if (c < 0x80) {\n length += 1;\n }\n else if (c < 0x800) {\n length += 2;\n }\n else if (c < 0xd800 || c >= 0xe000) {\n length += 3;\n }\n else {\n i++;\n length += 4;\n }\n }\n return length;\n}\n\nfunction _encode(bytes, defers, value) {\n var type = typeof value, i = 0, l = 0, hi = 0, lo = 0, length = 0, size = 0;\n\n if (type === 'string') {\n length = utf8Length(value);\n\n // fixstr\n if (length < 0x20) {\n bytes.push(length | 0xa0);\n size = 1;\n }\n // str 8\n else if (length < 0x100) {\n bytes.push(0xd9, length);\n size = 2;\n }\n // str 16\n else if (length < 0x10000) {\n bytes.push(0xda, length >> 8, length);\n size = 3;\n }\n // str 32\n else if (length < 0x100000000) {\n bytes.push(0xdb, length >> 24, length >> 16, length >> 8, length);\n size = 5;\n } else {\n throw new Error('String too long');\n }\n defers.push({ _str: value, _length: length, _offset: bytes.length });\n return size + length;\n }\n if (type === 'number') {\n // TODO: encode to float 32?\n\n // float 64\n if (Math.floor(value) !== value || !isFinite(value)) {\n bytes.push(0xcb);\n defers.push({ _float: value, _length: 8, _offset: bytes.length });\n return 9;\n }\n\n if (value >= 0) {\n // positive fixnum\n if (value < 0x80) {\n bytes.push(value);\n return 1;\n }\n // uint 8\n if (value < 0x100) {\n bytes.push(0xcc, value);\n return 2;\n }\n // uint 16\n if (value < 0x10000) {\n bytes.push(0xcd, value >> 8, value);\n return 3;\n }\n // uint 32\n if (value < 0x100000000) {\n bytes.push(0xce, value >> 24, value >> 16, value >> 8, value);\n return 5;\n }\n // uint 64\n hi = (value / Math.pow(2, 32)) >> 0;\n lo = value >>> 0;\n bytes.push(0xcf, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);\n return 9;\n } else {\n // negative fixnum\n if (value >= -0x20) {\n bytes.push(value);\n return 1;\n }\n // int 8\n if (value >= -0x80) {\n bytes.push(0xd0, value);\n return 2;\n }\n // int 16\n if (value >= -0x8000) {\n bytes.push(0xd1, value >> 8, value);\n return 3;\n }\n // int 32\n if (value >= -0x80000000) {\n bytes.push(0xd2, value >> 24, value >> 16, value >> 8, value);\n return 5;\n }\n // int 64\n hi = Math.floor(value / Math.pow(2, 32));\n lo = value >>> 0;\n bytes.push(0xd3, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);\n return 9;\n }\n }\n if (type === 'object') {\n // nil\n if (value === null) {\n bytes.push(0xc0);\n return 1;\n }\n\n if (Array.isArray(value)) {\n length = value.length;\n\n // fixarray\n if (length < 0x10) {\n bytes.push(length | 0x90);\n size = 1;\n }\n // array 16\n else if (length < 0x10000) {\n bytes.push(0xdc, length >> 8, length);\n size = 3;\n }\n // array 32\n else if (length < 0x100000000) {\n bytes.push(0xdd, length >> 24, length >> 16, length >> 8, length);\n size = 5;\n } else {\n throw new Error('Array too large');\n }\n for (i = 0; i < length; i++) {\n size += _encode(bytes, defers, value[i]);\n }\n return size;\n }\n\n // fixext 8 / Date\n if (value instanceof Date) {\n var time = value.getTime();\n hi = Math.floor(time / Math.pow(2, 32));\n lo = time >>> 0;\n bytes.push(0xd7, 0, hi >> 24, hi >> 16, hi >> 8, hi, lo >> 24, lo >> 16, lo >> 8, lo);\n return 10;\n }\n\n if (value instanceof ArrayBuffer) {\n length = value.byteLength;\n\n // bin 8\n if (length < 0x100) {\n bytes.push(0xc4, length);\n size = 2;\n } else\n // bin 16\n if (length < 0x10000) {\n bytes.push(0xc5, length >> 8, length);\n size = 3;\n } else\n // bin 32\n if (length < 0x100000000) {\n bytes.push(0xc6, length >> 24, length >> 16, length >> 8, length);\n size = 5;\n } else {\n throw new Error('Buffer too large');\n }\n defers.push({ _bin: value, _length: length, _offset: bytes.length });\n return size + length;\n }\n\n if (typeof value.toJSON === 'function') {\n return _encode(bytes, defers, value.toJSON());\n }\n\n var keys = [], key = '';\n\n var allKeys = Object.keys(value);\n for (i = 0, l = allKeys.length; i < l; i++) {\n key = allKeys[i];\n if (typeof value[key] !== 'function') {\n keys.push(key);\n }\n }\n length = keys.length;\n\n // fixmap\n if (length < 0x10) {\n bytes.push(length | 0x80);\n size = 1;\n }\n // map 16\n else if (length < 0x10000) {\n bytes.push(0xde, length >> 8, length);\n size = 3;\n }\n // map 32\n else if (length < 0x100000000) {\n bytes.push(0xdf, length >> 24, length >> 16, length >> 8, length);\n size = 5;\n } else {\n throw new Error('Object too large');\n }\n\n for (i = 0; i < length; i++) {\n key = keys[i];\n size += _encode(bytes, defers, key);\n size += _encode(bytes, defers, value[key]);\n }\n return size;\n }\n // false/true\n if (type === 'boolean') {\n bytes.push(value ? 0xc3 : 0xc2);\n return 1;\n }\n // fixext 1 / undefined\n if (type === 'undefined') {\n bytes.push(0xd4, 0, 0);\n return 3;\n }\n throw new Error('Could not encode');\n}\n\nfunction encode(value) {\n var bytes = [];\n var defers = [];\n var size = _encode(bytes, defers, value);\n var buf = new ArrayBuffer(size);\n var view = new DataView(buf);\n\n var deferIndex = 0;\n var deferWritten = 0;\n var nextOffset = -1;\n if (defers.length > 0) {\n nextOffset = defers[0]._offset;\n }\n\n var defer, deferLength = 0, offset = 0;\n for (var i = 0, l = bytes.length; i < l; i++) {\n view.setUint8(deferWritten + i, bytes[i]);\n if (i + 1 !== nextOffset) { continue; }\n defer = defers[deferIndex];\n deferLength = defer._length;\n offset = deferWritten + nextOffset;\n if (defer._bin) {\n var bin = new Uint8Array(defer._bin);\n for (var j = 0; j < deferLength; j++) {\n view.setUint8(offset + j, bin[j]);\n }\n } else if (defer._str) {\n utf8Write(view, offset, defer._str);\n } else if (defer._float !== undefined) {\n view.setFloat64(offset, defer._float);\n }\n deferIndex++;\n deferWritten += deferLength;\n if (defers[deferIndex]) {\n nextOffset = defers[deferIndex]._offset;\n }\n }\n return buf;\n}\n\nmodule.exports = encode;\n","'use strict';\n\nfunction Decoder(buffer) {\n this._offset = 0;\n if (buffer instanceof ArrayBuffer) {\n this._buffer = buffer;\n this._view = new DataView(this._buffer);\n } else if (ArrayBuffer.isView(buffer)) {\n this._buffer = buffer.buffer;\n this._view = new DataView(this._buffer, buffer.byteOffset, buffer.byteLength);\n } else {\n throw new Error('Invalid argument');\n }\n}\n\nfunction utf8Read(view, offset, length) {\n var string = '', chr = 0;\n for (var i = offset, end = offset + length; i < end; i++) {\n var byte = view.getUint8(i);\n if ((byte & 0x80) === 0x00) {\n string += String.fromCharCode(byte);\n continue;\n }\n if ((byte & 0xe0) === 0xc0) {\n string += String.fromCharCode(\n ((byte & 0x1f) << 6) |\n (view.getUint8(++i) & 0x3f)\n );\n continue;\n }\n if ((byte & 0xf0) === 0xe0) {\n string += String.fromCharCode(\n ((byte & 0x0f) << 12) |\n ((view.getUint8(++i) & 0x3f) << 6) |\n ((view.getUint8(++i) & 0x3f) << 0)\n );\n continue;\n }\n if ((byte & 0xf8) === 0xf0) {\n chr = ((byte & 0x07) << 18) |\n ((view.getUint8(++i) & 0x3f) << 12) |\n ((view.getUint8(++i) & 0x3f) << 6) |\n ((view.getUint8(++i) & 0x3f) << 0);\n if (chr >= 0x010000) { // surrogate pair\n chr -= 0x010000;\n string += String.fromCharCode((chr >>> 10) + 0xD800, (chr & 0x3FF) + 0xDC00);\n } else {\n string += String.fromCharCode(chr);\n }\n continue;\n }\n throw new Error('Invalid byte ' + byte.toString(16));\n }\n return string;\n}\n\nDecoder.prototype._array = function (length) {\n var value = new Array(length);\n for (var i = 0; i < length; i++) {\n value[i] = this._parse();\n }\n return value;\n};\n\nDecoder.prototype._map = function (length) {\n var key = '', value = {};\n for (var i = 0; i < length; i++) {\n key = this._parse();\n value[key] = this._parse();\n }\n return value;\n};\n\nDecoder.prototype._str = function (length) {\n var value = utf8Read(this._view, this._offset, length);\n this._offset += length;\n return value;\n};\n\nDecoder.prototype._bin = function (length) {\n var value = this._buffer.slice(this._offset, this._offset + length);\n this._offset += length;\n return value;\n};\n\nDecoder.prototype._parse = function () {\n var prefix = this._view.getUint8(this._offset++);\n var value, length = 0, type = 0, hi = 0, lo = 0;\n\n if (prefix < 0xc0) {\n // positive fixint\n if (prefix < 0x80) {\n return prefix;\n }\n // fixmap\n if (prefix < 0x90) {\n return this._map(prefix & 0x0f);\n }\n // fixarray\n if (prefix < 0xa0) {\n return this._array(prefix & 0x0f);\n }\n // fixstr\n return this._str(prefix & 0x1f);\n }\n\n // negative fixint\n if (prefix > 0xdf) {\n return (0xff - prefix + 1) * -1;\n }\n\n switch (prefix) {\n // nil\n case 0xc0:\n return null;\n // false\n case 0xc2:\n return false;\n // true\n case 0xc3:\n return true;\n\n // bin\n case 0xc4:\n length = this._view.getUint8(this._offset);\n this._offset += 1;\n return this._bin(length);\n case 0xc5:\n length = this._view.getUint16(this._offset);\n this._offset += 2;\n return this._bin(length);\n case 0xc6:\n length = this._view.getUint32(this._offset);\n this._offset += 4;\n return this._bin(length);\n\n // ext\n case 0xc7:\n length = this._view.getUint8(this._offset);\n type = this._view.getInt8(this._offset + 1);\n this._offset += 2;\n return [type, this._bin(length)];\n case 0xc8:\n length = this._view.getUint16(this._offset);\n type = this._view.getInt8(this._offset + 2);\n this._offset += 3;\n return [type, this._bin(length)];\n case 0xc9:\n length = this._view.getUint32(this._offset);\n type = this._view.getInt8(this._offset + 4);\n this._offset += 5;\n return [type, this._bin(length)];\n\n // float\n case 0xca:\n value = this._view.getFloat32(this._offset);\n this._offset += 4;\n return value;\n case 0xcb:\n value = this._view.getFloat64(this._offset);\n this._offset += 8;\n return value;\n\n // uint\n case 0xcc:\n value = this._view.getUint8(this._offset);\n this._offset += 1;\n return value;\n case 0xcd:\n value = this._view.getUint16(this._offset);\n this._offset += 2;\n return value;\n case 0xce:\n value = this._view.getUint32(this._offset);\n this._offset += 4;\n return value;\n case 0xcf:\n hi = this._view.getUint32(this._offset) * Math.pow(2, 32);\n lo = this._view.getUint32(this._offset + 4);\n this._offset += 8;\n return hi + lo;\n\n // int\n case 0xd0:\n value = this._view.getInt8(this._offset);\n this._offset += 1;\n return value;\n case 0xd1:\n value = this._view.getInt16(this._offset);\n this._offset += 2;\n return value;\n case 0xd2:\n value = this._view.getInt32(this._offset);\n this._offset += 4;\n return value;\n case 0xd3:\n hi = this._view.getInt32(this._offset) * Math.pow(2, 32);\n lo = this._view.getUint32(this._offset + 4);\n this._offset += 8;\n return hi + lo;\n\n // fixext\n case 0xd4:\n type = this._view.getInt8(this._offset);\n this._offset += 1;\n if (type === 0x00) {\n this._offset += 1;\n return void 0;\n }\n return [type, this._bin(1)];\n case 0xd5:\n type = this._view.getInt8(this._offset);\n this._offset += 1;\n return [type, this._bin(2)];\n case 0xd6:\n type = this._view.getInt8(this._offset);\n this._offset += 1;\n return [type, this._bin(4)];\n case 0xd7:\n type = this._view.getInt8(this._offset);\n this._offset += 1;\n if (type === 0x00) {\n hi = this._view.getInt32(this._offset) * Math.pow(2, 32);\n lo = this._view.getUint32(this._offset + 4);\n this._offset += 8;\n return new Date(hi + lo);\n }\n return [type, this._bin(8)];\n case 0xd8:\n type = this._view.getInt8(this._offset);\n this._offset += 1;\n return [type, this._bin(16)];\n\n // str\n case 0xd9:\n length = this._view.getUint8(this._offset);\n this._offset += 1;\n return this._str(length);\n case 0xda:\n length = this._view.getUint16(this._offset);\n this._offset += 2;\n return this._str(length);\n case 0xdb:\n length = this._view.getUint32(this._offset);\n this._offset += 4;\n return this._str(length);\n\n // array\n case 0xdc:\n length = this._view.getUint16(this._offset);\n this._offset += 2;\n return this._array(length);\n case 0xdd:\n length = this._view.getUint32(this._offset);\n this._offset += 4;\n return this._array(length);\n\n // map\n case 0xde:\n length = this._view.getUint16(this._offset);\n this._offset += 2;\n return this._map(length);\n case 0xdf:\n length = this._view.getUint32(this._offset);\n this._offset += 4;\n return this._map(length);\n }\n\n throw new Error('Could not parse');\n};\n\nfunction decode(buffer) {\n var decoder = new Decoder(buffer);\n var value = decoder._parse();\n if (decoder._offset !== buffer.byteLength) {\n throw new Error((buffer.byteLength - decoder._offset) + ' trailing bytes');\n }\n return value;\n}\n\nmodule.exports = decode;\n","exports.encode = require('./encode');\nexports.decode = require('./decode');\n","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n // Remove event specific arrays for event types that no\r\n // one is subscribed for to avoid memory leak.\r\n if (callbacks.length === 0) {\r\n delete this._callbacks['$' + event];\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n\r\n var args = new Array(arguments.length - 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n for (var i = 1; i < arguments.length; i++) {\r\n args[i - 1] = arguments[i];\r\n }\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n","var msgpack = require(\"notepack.io\");\nvar Emitter = require(\"component-emitter\");\n\nexports.protocol = 5;\n\n/**\n * Packet types (see https://github.com/socketio/socket.io-protocol)\n */\n\nvar PacketType = (exports.PacketType = {\n CONNECT: 0,\n DISCONNECT: 1,\n EVENT: 2,\n ACK: 3,\n CONNECT_ERROR: 4,\n});\n\nvar isInteger =\n Number.isInteger ||\n function (value) {\n return (\n typeof value === \"number\" &&\n isFinite(value) &&\n Math.floor(value) === value\n );\n };\n\nvar isString = function (value) {\n return typeof value === \"string\";\n};\n\nvar isObject = function (value) {\n return Object.prototype.toString.call(value) === \"[object Object]\";\n};\n\nfunction Encoder() {}\n\nEncoder.prototype.encode = function (packet) {\n return [msgpack.encode(packet)];\n};\n\nfunction Decoder() {}\n\nEmitter(Decoder.prototype);\n\nDecoder.prototype.add = function (obj) {\n var decoded = msgpack.decode(obj);\n this.checkPacket(decoded);\n this.emit(\"decoded\", decoded);\n};\n\nfunction isDataValid(decoded) {\n switch (decoded.type) {\n case PacketType.CONNECT:\n return decoded.data === undefined || isObject(decoded.data);\n case PacketType.DISCONNECT:\n return decoded.data === undefined;\n case PacketType.CONNECT_ERROR:\n return isString(decoded.data) || isObject(decoded.data);\n default:\n return Array.isArray(decoded.data);\n }\n}\n\nDecoder.prototype.checkPacket = function (decoded) {\n var isTypeValid =\n isInteger(decoded.type) &&\n decoded.type >= PacketType.CONNECT &&\n decoded.type <= PacketType.CONNECT_ERROR;\n if (!isTypeValid) {\n throw new Error(\"invalid packet type\");\n }\n\n if (!isString(decoded.nsp)) {\n throw new Error(\"invalid namespace\");\n }\n\n if (!isDataValid(decoded)) {\n throw new Error(\"invalid payload\");\n }\n\n var isAckValid = decoded.id === undefined || isInteger(decoded.id);\n if (!isAckValid) {\n throw new Error(\"invalid packet id\");\n }\n};\n\nDecoder.prototype.destroy = function () {};\n\nexports.Encoder = Encoder;\nexports.Decoder = Decoder;\n","export function on(obj, ev, fn) {\n obj.on(ev, fn);\n return function subDestroy() {\n obj.off(ev, fn);\n };\n}\n","import { PacketType } from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n connect: 1,\n connect_error: 1,\n disconnect: 1,\n disconnecting: 1,\n // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n newListener: 1,\n removeListener: 1,\n});\nexport class Socket extends Emitter {\n /**\n * `Socket` constructor.\n *\n * @public\n */\n constructor(io, nsp, opts) {\n super();\n this.connected = false;\n this.receiveBuffer = [];\n this.sendBuffer = [];\n this.ids = 0;\n this.acks = {};\n this.flags = {};\n this.io = io;\n this.nsp = nsp;\n if (opts && opts.auth) {\n this.auth = opts.auth;\n }\n if (this.io._autoConnect)\n this.open();\n }\n /**\n * Whether the socket is currently disconnected\n */\n get disconnected() {\n return !this.connected;\n }\n /**\n * Subscribe to open, close and packet events\n *\n * @private\n */\n subEvents() {\n if (this.subs)\n return;\n const io = this.io;\n this.subs = [\n on(io, \"open\", this.onopen.bind(this)),\n on(io, \"packet\", this.onpacket.bind(this)),\n on(io, \"error\", this.onerror.bind(this)),\n on(io, \"close\", this.onclose.bind(this)),\n ];\n }\n /**\n * Whether the Socket will try to reconnect when its Manager connects or reconnects\n */\n get active() {\n return !!this.subs;\n }\n /**\n * \"Opens\" the socket.\n *\n * @public\n */\n connect() {\n if (this.connected)\n return this;\n this.subEvents();\n if (!this.io[\"_reconnecting\"])\n this.io.open(); // ensure open\n if (\"open\" === this.io._readyState)\n this.onopen();\n return this;\n }\n /**\n * Alias for connect()\n */\n open() {\n return this.connect();\n }\n /**\n * Sends a `message` event.\n *\n * @return self\n * @public\n */\n send(...args) {\n args.unshift(\"message\");\n this.emit.apply(this, args);\n return this;\n }\n /**\n * Override `emit`.\n * If the event is in `events`, it's emitted normally.\n *\n * @return self\n * @public\n */\n emit(ev, ...args) {\n if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n throw new Error('\"' + ev + '\" is a reserved event name');\n }\n args.unshift(ev);\n const packet = {\n type: PacketType.EVENT,\n data: args,\n };\n packet.options = {};\n packet.options.compress = this.flags.compress !== false;\n // event ack callback\n if (\"function\" === typeof args[args.length - 1]) {\n const id = this.ids++;\n const ack = args.pop();\n this._registerAckCallback(id, ack);\n packet.id = id;\n }\n const isTransportWritable = this.io.engine &&\n this.io.engine.transport &&\n this.io.engine.transport.writable;\n const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);\n if (discardPacket) {\n }\n else if (this.connected) {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n }\n else {\n this.sendBuffer.push(packet);\n }\n this.flags = {};\n return this;\n }\n /**\n * @private\n */\n _registerAckCallback(id, ack) {\n const timeout = this.flags.timeout;\n if (timeout === undefined) {\n this.acks[id] = ack;\n return;\n }\n // @ts-ignore\n const timer = this.io.setTimeoutFn(() => {\n delete this.acks[id];\n for (let i = 0; i < this.sendBuffer.length; i++) {\n if (this.sendBuffer[i].id === id) {\n this.sendBuffer.splice(i, 1);\n }\n }\n ack.call(this, new Error(\"operation has timed out\"));\n }, timeout);\n this.acks[id] = (...args) => {\n // @ts-ignore\n this.io.clearTimeoutFn(timer);\n ack.apply(this, [null, ...args]);\n };\n }\n /**\n * Sends a packet.\n *\n * @param packet\n * @private\n */\n packet(packet) {\n packet.nsp = this.nsp;\n this.io._packet(packet);\n }\n /**\n * Called upon engine `open`.\n *\n * @private\n */\n onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: PacketType.CONNECT, data: this.auth });\n }\n }\n /**\n * Called upon engine or manager `error`.\n *\n * @param err\n * @private\n */\n onerror(err) {\n if (!this.connected) {\n this.emitReserved(\"connect_error\", err);\n }\n }\n /**\n * Called upon engine `close`.\n *\n * @param reason\n * @param description\n * @private\n */\n onclose(reason, description) {\n this.connected = false;\n delete this.id;\n this.emitReserved(\"disconnect\", reason, description);\n }\n /**\n * Called with socket packet.\n *\n * @param packet\n * @private\n */\n onpacket(packet) {\n const sameNamespace = packet.nsp === this.nsp;\n if (!sameNamespace)\n return;\n switch (packet.type) {\n case PacketType.CONNECT:\n if (packet.data && packet.data.sid) {\n const id = packet.data.sid;\n this.onconnect(id);\n }\n else {\n this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n }\n break;\n case PacketType.EVENT:\n case PacketType.BINARY_EVENT:\n this.onevent(packet);\n break;\n case PacketType.ACK:\n case PacketType.BINARY_ACK:\n this.onack(packet);\n break;\n case PacketType.DISCONNECT:\n this.ondisconnect();\n break;\n case PacketType.CONNECT_ERROR:\n this.destroy();\n const err = new Error(packet.data.message);\n // @ts-ignore\n err.data = packet.data.data;\n this.emitReserved(\"connect_error\", err);\n break;\n }\n }\n /**\n * Called upon a server event.\n *\n * @param packet\n * @private\n */\n onevent(packet) {\n const args = packet.data || [];\n if (null != packet.id) {\n args.push(this.ack(packet.id));\n }\n if (this.connected) {\n this.emitEvent(args);\n }\n else {\n this.receiveBuffer.push(Object.freeze(args));\n }\n }\n emitEvent(args) {\n if (this._anyListeners && this._anyListeners.length) {\n const listeners = this._anyListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, args);\n }\n }\n super.emit.apply(this, args);\n }\n /**\n * Produces an ack callback to emit with an event.\n *\n * @private\n */\n ack(id) {\n const self = this;\n let sent = false;\n return function (...args) {\n // prevent double callbacks\n if (sent)\n return;\n sent = true;\n self.packet({\n type: PacketType.ACK,\n id: id,\n data: args,\n });\n };\n }\n /**\n * Called upon a server acknowlegement.\n *\n * @param packet\n * @private\n */\n onack(packet) {\n const ack = this.acks[packet.id];\n if (\"function\" === typeof ack) {\n ack.apply(this, packet.data);\n delete this.acks[packet.id];\n }\n else {\n }\n }\n /**\n * Called upon server connect.\n *\n * @private\n */\n onconnect(id) {\n this.id = id;\n this.connected = true;\n this.emitBuffered();\n this.emitReserved(\"connect\");\n }\n /**\n * Emit buffered events (received and emitted).\n *\n * @private\n */\n emitBuffered() {\n this.receiveBuffer.forEach((args) => this.emitEvent(args));\n this.receiveBuffer = [];\n this.sendBuffer.forEach((packet) => {\n this.notifyOutgoingListeners(packet);\n this.packet(packet);\n });\n this.sendBuffer = [];\n }\n /**\n * Called upon server disconnect.\n *\n * @private\n */\n ondisconnect() {\n this.destroy();\n this.onclose(\"io server disconnect\");\n }\n /**\n * Called upon forced client/server side disconnections,\n * this method ensures the manager stops tracking us and\n * that reconnections don't get triggered for this.\n *\n * @private\n */\n destroy() {\n if (this.subs) {\n // clean subscriptions to avoid reconnections\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs = undefined;\n }\n this.io[\"_destroy\"](this);\n }\n /**\n * Disconnects the socket manually.\n *\n * @return self\n * @public\n */\n disconnect() {\n if (this.connected) {\n this.packet({ type: PacketType.DISCONNECT });\n }\n // remove socket from pool\n this.destroy();\n if (this.connected) {\n // fire events\n this.onclose(\"io client disconnect\");\n }\n return this;\n }\n /**\n * Alias for disconnect()\n *\n * @return self\n * @public\n */\n close() {\n return this.disconnect();\n }\n /**\n * Sets the compress flag.\n *\n * @param compress - if `true`, compresses the sending data\n * @return self\n * @public\n */\n compress(compress) {\n this.flags.compress = compress;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n * ready to send messages.\n *\n * @returns self\n * @public\n */\n get volatile() {\n this.flags.volatile = true;\n return this;\n }\n /**\n * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n * given number of milliseconds have elapsed without an acknowledgement from the server:\n *\n * ```\n * socket.timeout(5000).emit(\"my-event\", (err) => {\n * if (err) {\n * // the server did not acknowledge the event in the given delay\n * }\n * });\n * ```\n *\n * @returns self\n * @public\n */\n timeout(timeout) {\n this.flags.timeout = timeout;\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n * @public\n */\n onAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n * @public\n */\n prependAny(listener) {\n this._anyListeners = this._anyListeners || [];\n this._anyListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n * @public\n */\n offAny(listener) {\n if (!this._anyListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAny() {\n return this._anyListeners || [];\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback.\n *\n * @param listener\n *\n *
\n     *\n     * socket.onAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n onAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.push(listener);\n return this;\n }\n /**\n * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n * callback. The listener is added to the beginning of the listeners array.\n *\n * @param listener\n *\n *
\n     *\n     * socket.prependAnyOutgoing((event, ...args) => {\n     *   console.log(event);\n     * });\n     *\n     * 
\n *\n * @public\n */\n prependAnyOutgoing(listener) {\n this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n this._anyOutgoingListeners.unshift(listener);\n return this;\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param listener\n *\n *
\n     *\n     * const handler = (event, ...args) => {\n     *   console.log(event);\n     * }\n     *\n     * socket.onAnyOutgoing(handler);\n     *\n     * // then later\n     * socket.offAnyOutgoing(handler);\n     *\n     * 
\n *\n * @public\n */\n offAnyOutgoing(listener) {\n if (!this._anyOutgoingListeners) {\n return this;\n }\n if (listener) {\n const listeners = this._anyOutgoingListeners;\n for (let i = 0; i < listeners.length; i++) {\n if (listener === listeners[i]) {\n listeners.splice(i, 1);\n return this;\n }\n }\n }\n else {\n this._anyOutgoingListeners = [];\n }\n return this;\n }\n /**\n * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n * e.g. to remove listeners.\n *\n * @public\n */\n listenersAnyOutgoing() {\n return this._anyOutgoingListeners || [];\n }\n /**\n * Notify the listeners for each packet sent\n *\n * @param packet\n *\n * @private\n */\n notifyOutgoingListeners(packet) {\n if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n const listeners = this._anyOutgoingListeners.slice();\n for (const listener of listeners) {\n listener.apply(this, packet.data);\n }\n }\n }\n}\n","/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nexport function Backoff(opts) {\n opts = opts || {};\n this.ms = opts.min || 100;\n this.max = opts.max || 10000;\n this.factor = opts.factor || 2;\n this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n var ms = this.ms * Math.pow(this.factor, this.attempts++);\n if (this.jitter) {\n var rand = Math.random();\n var deviation = Math.floor(rand * this.jitter * ms);\n ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n }\n return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n this.jitter = jitter;\n};\n","import { Socket as Engine, installTimerFunctions, } from \"engine.io-client\";\nimport { Socket } from \"./socket.js\";\nimport * as parser from \"socket.io-parser\";\nimport { on } from \"./on.js\";\nimport { Backoff } from \"./contrib/backo2.js\";\nimport { Emitter, } from \"@socket.io/component-emitter\";\nexport class Manager extends Emitter {\n constructor(uri, opts) {\n var _a;\n super();\n this.nsps = {};\n this.subs = [];\n if (uri && \"object\" === typeof uri) {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n opts.path = opts.path || \"/socket.io\";\n this.opts = opts;\n installTimerFunctions(this, opts);\n this.reconnection(opts.reconnection !== false);\n this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n this.reconnectionDelay(opts.reconnectionDelay || 1000);\n this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n this.backoff = new Backoff({\n min: this.reconnectionDelay(),\n max: this.reconnectionDelayMax(),\n jitter: this.randomizationFactor(),\n });\n this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n this._readyState = \"closed\";\n this.uri = uri;\n const _parser = opts.parser || parser;\n this.encoder = new _parser.Encoder();\n this.decoder = new _parser.Decoder();\n this._autoConnect = opts.autoConnect !== false;\n if (this._autoConnect)\n this.open();\n }\n reconnection(v) {\n if (!arguments.length)\n return this._reconnection;\n this._reconnection = !!v;\n return this;\n }\n reconnectionAttempts(v) {\n if (v === undefined)\n return this._reconnectionAttempts;\n this._reconnectionAttempts = v;\n return this;\n }\n reconnectionDelay(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelay;\n this._reconnectionDelay = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n return this;\n }\n randomizationFactor(v) {\n var _a;\n if (v === undefined)\n return this._randomizationFactor;\n this._randomizationFactor = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n return this;\n }\n reconnectionDelayMax(v) {\n var _a;\n if (v === undefined)\n return this._reconnectionDelayMax;\n this._reconnectionDelayMax = v;\n (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n return this;\n }\n timeout(v) {\n if (!arguments.length)\n return this._timeout;\n this._timeout = v;\n return this;\n }\n /**\n * Starts trying to reconnect if reconnection is enabled and we have not\n * started reconnecting yet\n *\n * @private\n */\n maybeReconnectOnOpen() {\n // Only try to reconnect if it's the first time we're connecting\n if (!this._reconnecting &&\n this._reconnection &&\n this.backoff.attempts === 0) {\n // keeps reconnection from firing twice for the same reconnection loop\n this.reconnect();\n }\n }\n /**\n * Sets the current transport `socket`.\n *\n * @param {Function} fn - optional, callback\n * @return self\n * @public\n */\n open(fn) {\n if (~this._readyState.indexOf(\"open\"))\n return this;\n this.engine = new Engine(this.uri, this.opts);\n const socket = this.engine;\n const self = this;\n this._readyState = \"opening\";\n this.skipReconnect = false;\n // emit `open`\n const openSubDestroy = on(socket, \"open\", function () {\n self.onopen();\n fn && fn();\n });\n // emit `error`\n const errorSub = on(socket, \"error\", (err) => {\n self.cleanup();\n self._readyState = \"closed\";\n this.emitReserved(\"error\", err);\n if (fn) {\n fn(err);\n }\n else {\n // Only do this if there is no fn to handle the error\n self.maybeReconnectOnOpen();\n }\n });\n if (false !== this._timeout) {\n const timeout = this._timeout;\n if (timeout === 0) {\n openSubDestroy(); // prevents a race condition with the 'open' event\n }\n // set timer\n const timer = this.setTimeoutFn(() => {\n openSubDestroy();\n socket.close();\n // @ts-ignore\n socket.emit(\"error\", new Error(\"timeout\"));\n }, timeout);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n this.subs.push(openSubDestroy);\n this.subs.push(errorSub);\n return this;\n }\n /**\n * Alias for open()\n *\n * @return self\n * @public\n */\n connect(fn) {\n return this.open(fn);\n }\n /**\n * Called upon transport open.\n *\n * @private\n */\n onopen() {\n // clear old subs\n this.cleanup();\n // mark as open\n this._readyState = \"open\";\n this.emitReserved(\"open\");\n // add new subs\n const socket = this.engine;\n this.subs.push(on(socket, \"ping\", this.onping.bind(this)), on(socket, \"data\", this.ondata.bind(this)), on(socket, \"error\", this.onerror.bind(this)), on(socket, \"close\", this.onclose.bind(this)), on(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n }\n /**\n * Called upon a ping.\n *\n * @private\n */\n onping() {\n this.emitReserved(\"ping\");\n }\n /**\n * Called with data.\n *\n * @private\n */\n ondata(data) {\n this.decoder.add(data);\n }\n /**\n * Called when parser fully decodes a packet.\n *\n * @private\n */\n ondecoded(packet) {\n this.emitReserved(\"packet\", packet);\n }\n /**\n * Called upon socket error.\n *\n * @private\n */\n onerror(err) {\n this.emitReserved(\"error\", err);\n }\n /**\n * Creates a new socket for the given `nsp`.\n *\n * @return {Socket}\n * @public\n */\n socket(nsp, opts) {\n let socket = this.nsps[nsp];\n if (!socket) {\n socket = new Socket(this, nsp, opts);\n this.nsps[nsp] = socket;\n }\n return socket;\n }\n /**\n * Called upon a socket close.\n *\n * @param socket\n * @private\n */\n _destroy(socket) {\n const nsps = Object.keys(this.nsps);\n for (const nsp of nsps) {\n const socket = this.nsps[nsp];\n if (socket.active) {\n return;\n }\n }\n this._close();\n }\n /**\n * Writes a packet.\n *\n * @param packet\n * @private\n */\n _packet(packet) {\n const encodedPackets = this.encoder.encode(packet);\n for (let i = 0; i < encodedPackets.length; i++) {\n this.engine.write(encodedPackets[i], packet.options);\n }\n }\n /**\n * Clean up transport subscriptions and packet buffer.\n *\n * @private\n */\n cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }\n /**\n * Close the current socket.\n *\n * @private\n */\n _close() {\n this.skipReconnect = true;\n this._reconnecting = false;\n this.onclose(\"forced close\");\n if (this.engine)\n this.engine.close();\n }\n /**\n * Alias for close()\n *\n * @private\n */\n disconnect() {\n return this._close();\n }\n /**\n * Called upon engine close.\n *\n * @private\n */\n onclose(reason, description) {\n this.cleanup();\n this.backoff.reset();\n this._readyState = \"closed\";\n this.emitReserved(\"close\", reason, description);\n if (this._reconnection && !this.skipReconnect) {\n this.reconnect();\n }\n }\n /**\n * Attempt a reconnection.\n *\n * @private\n */\n reconnect() {\n if (this._reconnecting || this.skipReconnect)\n return this;\n const self = this;\n if (this.backoff.attempts >= this._reconnectionAttempts) {\n this.backoff.reset();\n this.emitReserved(\"reconnect_failed\");\n this._reconnecting = false;\n }\n else {\n const delay = this.backoff.duration();\n this._reconnecting = true;\n const timer = this.setTimeoutFn(() => {\n if (self.skipReconnect)\n return;\n this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n // check again for the case socket closed in above events\n if (self.skipReconnect)\n return;\n self.open((err) => {\n if (err) {\n self._reconnecting = false;\n self.reconnect();\n this.emitReserved(\"reconnect_error\", err);\n }\n else {\n self.onreconnect();\n }\n });\n }, delay);\n if (this.opts.autoUnref) {\n timer.unref();\n }\n this.subs.push(function subDestroy() {\n clearTimeout(timer);\n });\n }\n }\n /**\n * Called upon successful reconnect.\n *\n * @private\n */\n onreconnect() {\n const attempt = this.backoff.attempts;\n this._reconnecting = false;\n this.backoff.reset();\n this.emitReserved(\"reconnect\", attempt);\n }\n}\n","import { url } from \"./url.js\";\nimport { Manager } from \"./manager.js\";\nimport { Socket } from \"./socket.js\";\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n if (typeof uri === \"object\") {\n opts = uri;\n uri = undefined;\n }\n opts = opts || {};\n const parsed = url(uri, opts.path || \"/socket.io\");\n const source = parsed.source;\n const id = parsed.id;\n const path = parsed.path;\n const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n const newConnection = opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n let io;\n if (newConnection) {\n io = new Manager(source, opts);\n }\n else {\n if (!cache[id]) {\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n Manager,\n Socket,\n io: lookup,\n connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nexport { protocol } from \"socket.io-parser\";\n/**\n * Expose constructors for standalone build.\n *\n * @public\n */\nexport { Manager, Socket, lookup as io, lookup as connect, lookup as default, };\n","import { parse } from \"engine.io-client\";\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n * Defaults to window.location.\n * @public\n */\nexport function url(uri, path = \"\", loc) {\n let obj = uri;\n // default to window.location\n loc = loc || (typeof location !== \"undefined\" && location);\n if (null == uri)\n uri = loc.protocol + \"//\" + loc.host;\n // relative path support\n if (typeof uri === \"string\") {\n if (\"/\" === uri.charAt(0)) {\n if (\"/\" === uri.charAt(1)) {\n uri = loc.protocol + uri;\n }\n else {\n uri = loc.host + uri;\n }\n }\n if (!/^(https?|wss?):\\/\\//.test(uri)) {\n if (\"undefined\" !== typeof loc) {\n uri = loc.protocol + \"//\" + uri;\n }\n else {\n uri = \"https://\" + uri;\n }\n }\n // parse\n obj = parse(uri);\n }\n // make sure we treat `localhost:80` and `localhost` equally\n if (!obj.port) {\n if (/^(http|ws)$/.test(obj.protocol)) {\n obj.port = \"80\";\n }\n else if (/^(http|ws)s$/.test(obj.protocol)) {\n obj.port = \"443\";\n }\n }\n obj.path = obj.path || \"/\";\n const ipv6 = obj.host.indexOf(\":\") !== -1;\n const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n // define unique id\n obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n // define href\n obj.href =\n obj.protocol +\n \"://\" +\n host +\n (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n return obj;\n}\n"],"names":["PACKET_TYPES","Object","create","PACKET_TYPES_REVERSE","keys","forEach","key","ERROR_PACKET","type","data","withNativeBlob","Blob","prototype","toString","call","withNativeArrayBuffer","ArrayBuffer","encodePacket","supportsBinary","callback","obj","encodeBlobAsBase64","isView","buffer","fileReader","FileReader","onload","content","result","split","readAsDataURL","chars","lookup","Uint8Array","i","length","charCodeAt","decodePacket","encodedPacket","binaryType","mapBinary","charAt","decodeBase64Packet","substring","decoded","base64","encoded1","encoded2","encoded3","encoded4","bufferLength","len","p","arraybuffer","bytes","decode","SEPARATOR","String","fromCharCode","Emitter","mixin","on","addEventListener","event","fn","_callbacks","this","push","once","off","apply","arguments","removeListener","removeAllListeners","removeEventListener","cb","callbacks","splice","emit","args","Array","slice","emitReserved","listeners","hasListeners","self","window","Function","pick","attr","reduce","acc","k","hasOwnProperty","NATIVE_SET_TIMEOUT","setTimeout","NATIVE_CLEAR_TIMEOUT","clearTimeout","installTimerFunctions","opts","useNativeTimers","setTimeoutFn","bind","globalThis","clearTimeoutFn","prev","TransportError","reason","description","context","Error","Transport","writable","query","readyState","socket","doOpen","doClose","onClose","packets","write","packet","onPacket","details","alphabet","map","seed","encode","num","encoded","Math","floor","yeast","now","Date","str","encodeURIComponent","qs","qry","pairs","l","pair","decodeURIComponent","value","XMLHttpRequest","err","hasCORS","xdomain","e","concat","join","empty","hasXHR2","responseType","Polling","polling","location","isSSL","protocol","port","xd","hostname","xs","secure","forceBase64","poll","onPause","pause","_this2","total","doPoll","encodedPayload","encodedPackets","decodedPacket","decodePayload","_this3","onOpen","close","_this4","count","encodePayload","_this5","doWrite","schema","timestampRequests","timestampParam","sid","b64","Number","encodedQuery","indexOf","path","Request","uri","req","request","method","xhrStatus","_this6","onError","onData","_this7","pollXhr","async","undefined","xscheme","xhr","open","extraHeaders","setDisableHeaderCheck","setRequestHeader","withCredentials","requestTimeout","timeout","onreadystatechange","status","_this9","onLoad","send","document","index","requestsCount","requests","cleanup","fromError","abort","responseText","attachEvent","unloadHandler","nextTick","Promise","resolve","then","WebSocket","MozWebSocket","isReactNative","navigator","product","toLowerCase","WS","check","protocols","headers","ws","addEventListeners","onopen","autoUnref","_socket","unref","onclose","closeEvent","onmessage","ev","onerror","lastPacket","name","transports","websocket","re","parts","parse","src","b","replace","m","exec","source","host","authority","ipv6uri","pathNames","regx","names","substr","queryKey","$0","$1","$2","Socket","_this","writeBuffer","prevBufferLen","_extends","agent","upgrade","rememberUpgrade","rejectUnauthorized","perMessageDeflate","threshold","transportOptions","closeOnBeforeunload","id","upgrades","pingInterval","pingTimeout","pingTimeoutTimer","transport","offlineEventListener","EIO","priorWebsocketSuccess","createTransport","shift","setTransport","onDrain","failed","onTransportOpen","msg","upgrading","flush","freezeTransport","error","onTransportClose","onupgrade","to","probe","onHandshake","JSON","resetPingTimeout","sendPacket","code","filterUpgrades","maxPayload","getWritablePackets","payloadSize","c","utf8Length","ceil","byteLength","size","options","compress","cleanupAndClose","waitForUpgrade","filteredUpgrades","j","utf8Write","view","offset","setUint8","_encode","defers","hi","lo","_str","_length","_offset","isFinite","pow","_float","isArray","time","getTime","_bin","toJSON","allKeys","encode_1","buf","DataView","deferIndex","deferWritten","nextOffset","defer","deferLength","bin","setFloat64","Decoder","_buffer","_view","byteOffset","_array","_parse","_map","string","chr","end","byte","getUint8","utf8Read","prefix","getUint16","getUint32","getInt8","getFloat32","getFloat64","getInt16","getInt32","decode_1","decoder","require$$0","require$$1","module","msgpack","PacketType","PacketType_1","CONNECT","DISCONNECT","EVENT","ACK","CONNECT_ERROR","isInteger","isString","isObject","Encoder","add","checkPacket","nsp","isDataValid","destroy","RESERVED_EVENTS","freeze","connect","connect_error","disconnect","disconnecting","newListener","io","connected","receiveBuffer","sendBuffer","ids","acks","flags","auth","_autoConnect","subs","onpacket","subEvents","_readyState","unshift","ack","pop","_registerAckCallback","isTransportWritable","engine","discardPacket","notifyOutgoingListeners","timer","_packet","onconnect","BINARY_EVENT","onevent","BINARY_ACK","onack","ondisconnect","message","emitEvent","_anyListeners","sent","emitBuffered","subDestroy","listener","_anyOutgoingListeners","Backoff","ms","min","max","factor","jitter","attempts","duration","rand","random","deviation","reset","setMin","setMax","setJitter","Manager","_a","nsps","reconnection","reconnectionAttempts","Infinity","reconnectionDelay","reconnectionDelayMax","randomizationFactor","backoff","_parser","parser","encoder","autoConnect","v","_reconnection","_reconnectionAttempts","_reconnectionDelay","_randomizationFactor","_reconnectionDelayMax","_timeout","_reconnecting","reconnect","Engine","skipReconnect","openSubDestroy","errorSub","maybeReconnectOnOpen","onping","ondata","ondecoded","active","_close","delay","onreconnect","attempt","cache","_typeof","parsed","loc","test","href","url","sameNamespace","forceNew","multiplex"],"mappings":";;;;;i1IAAA,IAAMA,EAAeC,OAAOC,OAAO,MACnCF,EAAY,KAAW,IACvBA,EAAY,MAAY,IACxBA,EAAY,KAAW,IACvBA,EAAY,KAAW,IACvBA,EAAY,QAAc,IAC1BA,EAAY,QAAc,IAC1BA,EAAY,KAAW,IACvB,IAAMG,EAAuBF,OAAOC,OAAO,MAC3CD,OAAOG,KAAKJ,GAAcK,SAAQ,SAAAC,GAC9BH,EAAqBH,EAAaM,IAAQA,KCN9C,IDQA,IAAMC,EAAe,CAAEC,KAAM,QAASC,KAAM,gBEXtCC,EAAiC,mBAATC,MACT,oBAATA,MACqC,6BAAzCV,OAAOW,UAAUC,SAASC,KAAKH,MACjCI,EAA+C,mBAAhBC,YAO/BC,EAAe,WAAiBC,EAAgBC,OALvCC,EAKSZ,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X"} \ No newline at end of file diff --git a/node_modules/socket.io-client/package.json b/node_modules/socket.io-client/package.json new file mode 100644 index 0000000..806973b --- /dev/null +++ b/node_modules/socket.io-client/package.json @@ -0,0 +1,122 @@ +{ + "name": "socket.io-client", + "version": "4.5.1", + "description": "Realtime application framework client", + "keywords": [ + "realtime", + "framework", + "websocket", + "tcp", + "events", + "client" + ], + "files": [ + "dist/", + "build/" + ], + "type": "commonjs", + "main": "./build/cjs/index.js", + "module": "./build/esm/index.js", + "exports": { + "./package.json": "./package.json", + "./dist/socket.io.js": "./dist/socket.io.js", + "./dist/socket.io.js.map": "./dist/socket.io.js.map", + ".": { + "import": { + "node": "./build/esm-debug/index.js", + "default": "./build/esm/index.js" + }, + "require": "./build/cjs/index.js", + "types": "./build/esm/index.d.ts" + } + }, + "types": "./build/esm/index.d.ts", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.2.1", + "socket.io-parser": "~4.2.0" + }, + "devDependencies": { + "@babel/core": "^7.15.0", + "@babel/plugin-transform-object-assign": "^7.14.5", + "@babel/preset-env": "^7.15.0", + "@rollup/plugin-alias": "^3.1.5", + "@rollup/plugin-babel": "^5.3.0", + "@rollup/plugin-commonjs": "^21.0.0", + "@rollup/plugin-node-resolve": "^13.0.5", + "@sinonjs/fake-timers": "^7.1.2", + "@types/mocha": "^9.0.0", + "@types/node": "^16.7.6", + "@types/sinonjs__fake-timers": "^6.0.3", + "babel-eslint": "^10.1.0", + "babel-loader": "^8.1.0", + "babel-preset-es2015": "6.24.1", + "base64-arraybuffer": "^0.1.5", + "expect.js": "0.3.1", + "has-cors": "^1.1.0", + "istanbul": "^0.4.5", + "mocha": "^3.3.0", + "prettier": "^2.3.2", + "rimraf": "^3.0.2", + "rollup": "^2.58.0", + "rollup-plugin-terser": "^7.0.2", + "socket.io": "3.0.0", + "socket.io-browsers": "^1.0.0", + "socket.io-msgpack-parser": "^3.0.0", + "text-blob-builder": "0.0.1", + "ts-loader": "^8.3.0", + "ts-node": "^10.2.1", + "tsd": "^0.17.0", + "typescript": "^4.4.2", + "webpack": "^4.44.2", + "webpack-cli": "^3.3.12", + "webpack-remove-debug": "^0.1.0", + "zuul": "~3.11.1", + "zuul-builder-webpack": "^1.2.0", + "zuul-ngrok": "4.0.0" + }, + "scripts": { + "compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh", + "test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi", + "test:node": "mocha --require ts-node/register --reporter dot --require test/support/server.js test/index.js", + "test:browser": "zuul test/index.js", + "test:types": "tsd", + "build": "rollup -c support/rollup.config.umd.js && rollup -c support/rollup.config.esm.js && rollup -c support/rollup.config.umd.msgpack.js", + "format:check": "prettier --check \"lib/**/*.ts\" \"test/**/*.js\" \"test/**/*.ts\" \"support/**/*.js\"", + "format:fix": "prettier --write \"lib/**/*.ts\" \"test/**/*.js\" \"test/**/*.ts\" \"support/**/*.js\"", + "prepack": "npm run compile" + }, + "contributors": [ + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Arnout Kazemier", + "email": "info@3rd-eden.com" + }, + { + "name": "Vladimir Dronnikov", + "email": "dronnikov@gmail.com" + }, + { + "name": "Einar Otto Stangvik", + "email": "einaros@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/socketio/socket.io-client.git" + }, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "tsd": { + "directory": "test" + }, + "browser": { + "./test/node.ts": false + } +} diff --git a/node_modules/socket.io-parser/LICENSE b/node_modules/socket.io-parser/LICENSE new file mode 100644 index 0000000..7e43606 --- /dev/null +++ b/node_modules/socket.io-parser/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2014 Guillermo Rauch + +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/node_modules/socket.io-parser/Readme.md b/node_modules/socket.io-parser/Readme.md new file mode 100644 index 0000000..e4f6a8a --- /dev/null +++ b/node_modules/socket.io-parser/Readme.md @@ -0,0 +1,81 @@ + +# socket.io-parser + +[![Build Status](https://github.com/socketio/socket.io-parser/workflows/CI/badge.svg)](https://github.com/socketio/socket.io-parser/actions) +[![NPM version](https://badge.fury.io/js/socket.io-parser.svg)](http://badge.fury.io/js/socket.io-parser) + +A socket.io encoder and decoder written in JavaScript complying with version `5` +of [socket.io-protocol](https://github.com/socketio/socket.io-protocol). +Used by [socket.io](https://github.com/automattic/socket.io) and +[socket.io-client](https://github.com/automattic/socket.io-client). + +Compatibility table: + +| Parser version | Socket.IO server version | Protocol revision | +|----------------| ------------------------ | ----------------- | +| 3.x | 1.x / 2.x | 4 | +| 4.x | 3.x | 5 | + + +## Parser API + + socket.io-parser is the reference implementation of socket.io-protocol. Read + the full API here: + [socket.io-protocol](https://github.com/learnboost/socket.io-protocol). + +## Example Usage + +### Encoding and decoding a packet + +```js +var parser = require('socket.io-parser'); +var encoder = new parser.Encoder(); +var packet = { + type: parser.EVENT, + data: 'test-packet', + id: 13 +}; +encoder.encode(packet, function(encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function(decodedPacket) { + // decodedPacket.type == parser.EVENT + // decodedPacket.data == 'test-packet' + // decodedPacket.id == 13 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); +``` + +### Encoding and decoding a packet with binary data + +```js +var parser = require('socket.io-parser'); +var encoder = new parser.Encoder(); +var packet = { + type: parser.BINARY_EVENT, + data: {i: new Buffer(1234), j: new Blob([new ArrayBuffer(2)])}, + id: 15 +}; +encoder.encode(packet, function(encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function(decodedPacket) { + // decodedPacket.type == parser.BINARY_EVENT + // Buffer.isBuffer(decodedPacket.data.i) == true + // Buffer.isBuffer(decodedPacket.data.j) == true + // decodedPacket.id == 15 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); +``` +See the test suite for more examples of how socket.io-parser is used. + + +## License + +MIT diff --git a/node_modules/socket.io-parser/build/cjs/binary.js b/node_modules/socket.io-parser/build/cjs/binary.js new file mode 100644 index 0000000..55d19eb --- /dev/null +++ b/node_modules/socket.io-parser/build/cjs/binary.js @@ -0,0 +1,88 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.reconstructPacket = exports.deconstructPacket = void 0; +const is_binary_js_1 = require("./is-binary.js"); +/** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ +function deconstructPacket(packet) { + const buffers = []; + const packetData = packet.data; + const pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + return { packet: pack, buffers: buffers }; +} +exports.deconstructPacket = deconstructPacket; +function _deconstructPacket(data, buffers) { + if (!data) + return data; + if (is_binary_js_1.isBinary(data)) { + const placeholder = { _placeholder: true, num: buffers.length }; + buffers.push(data); + return placeholder; + } + else if (Array.isArray(data)) { + const newData = new Array(data.length); + for (let i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + return newData; + } + else if (typeof data === "object" && !(data instanceof Date)) { + const newData = {}; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + newData[key] = _deconstructPacket(data[key], buffers); + } + } + return newData; + } + return data; +} +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ +function reconstructPacket(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + return packet; +} +exports.reconstructPacket = reconstructPacket; +function _reconstructPacket(data, buffers) { + if (!data) + return data; + if (data && data._placeholder === true) { + const isIndexValid = typeof data.num === "number" && + data.num >= 0 && + data.num < buffers.length; + if (isIndexValid) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } + else { + throw new Error("illegal attachments"); + } + } + else if (Array.isArray(data)) { + for (let i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } + else if (typeof data === "object") { + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + } + return data; +} diff --git a/node_modules/socket.io-parser/build/cjs/index.js b/node_modules/socket.io-parser/build/cjs/index.js new file mode 100644 index 0000000..8166a28 --- /dev/null +++ b/node_modules/socket.io-parser/build/cjs/index.js @@ -0,0 +1,298 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Decoder = exports.Encoder = exports.PacketType = exports.protocol = void 0; +const component_emitter_1 = require("@socket.io/component-emitter"); +const binary_js_1 = require("./binary.js"); +const is_binary_js_1 = require("./is-binary.js"); +const debug_1 = require("debug"); // debug() +const debug = debug_1.default("socket.io-parser"); // debug() +/** + * Protocol version. + * + * @public + */ +exports.protocol = 5; +var PacketType; +(function (PacketType) { + PacketType[PacketType["CONNECT"] = 0] = "CONNECT"; + PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT"; + PacketType[PacketType["EVENT"] = 2] = "EVENT"; + PacketType[PacketType["ACK"] = 3] = "ACK"; + PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR"; + PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT"; + PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK"; +})(PacketType = exports.PacketType || (exports.PacketType = {})); +/** + * A socket.io Encoder instance + */ +class Encoder { + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(replacer) { + this.replacer = replacer; + } + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + encode(obj) { + debug("encoding packet %j", obj); + if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) { + if (is_binary_js_1.hasBinary(obj)) { + obj.type = + obj.type === PacketType.EVENT + ? PacketType.BINARY_EVENT + : PacketType.BINARY_ACK; + return this.encodeAsBinary(obj); + } + } + return [this.encodeAsString(obj)]; + } + /** + * Encode packet as string. + */ + encodeAsString(obj) { + // first is type + let str = "" + obj.type; + // attachments if we have them + if (obj.type === PacketType.BINARY_EVENT || + obj.type === PacketType.BINARY_ACK) { + str += obj.attachments + "-"; + } + // if we have a namespace other than `/` + // we append it followed by a comma `,` + if (obj.nsp && "/" !== obj.nsp) { + str += obj.nsp + ","; + } + // immediately followed by the id + if (null != obj.id) { + str += obj.id; + } + // json data + if (null != obj.data) { + str += JSON.stringify(obj.data, this.replacer); + } + debug("encoded %j as %s", obj, str); + return str; + } + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + encodeAsBinary(obj) { + const deconstruction = binary_js_1.deconstructPacket(obj); + const pack = this.encodeAsString(deconstruction.packet); + const buffers = deconstruction.buffers; + buffers.unshift(pack); // add packet info to beginning of data list + return buffers; // write all the buffers + } +} +exports.Encoder = Encoder; +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ +class Decoder extends component_emitter_1.Emitter { + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(reviver) { + super(); + this.reviver = reviver; + } + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + add(obj) { + let packet; + if (typeof obj === "string") { + if (this.reconstructor) { + throw new Error("got plaintext data when reconstructing a packet"); + } + packet = this.decodeString(obj); + if (packet.type === PacketType.BINARY_EVENT || + packet.type === PacketType.BINARY_ACK) { + // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); + // no attachments, labeled binary but no binary data to follow + if (packet.attachments === 0) { + super.emitReserved("decoded", packet); + } + } + else { + // non-binary full packet + super.emitReserved("decoded", packet); + } + } + else if (is_binary_js_1.isBinary(obj) || obj.base64) { + // raw binary data + if (!this.reconstructor) { + throw new Error("got binary data when not reconstructing a packet"); + } + else { + packet = this.reconstructor.takeBinaryData(obj); + if (packet) { + // received final buffer + this.reconstructor = null; + super.emitReserved("decoded", packet); + } + } + } + else { + throw new Error("Unknown type: " + obj); + } + } + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + decodeString(str) { + let i = 0; + // look up type + const p = { + type: Number(str.charAt(0)), + }; + if (PacketType[p.type] === undefined) { + throw new Error("unknown packet type " + p.type); + } + // look up attachments if type binary + if (p.type === PacketType.BINARY_EVENT || + p.type === PacketType.BINARY_ACK) { + const start = i + 1; + while (str.charAt(++i) !== "-" && i != str.length) { } + const buf = str.substring(start, i); + if (buf != Number(buf) || str.charAt(i) !== "-") { + throw new Error("Illegal attachments"); + } + p.attachments = Number(buf); + } + // look up namespace (if any) + if ("/" === str.charAt(i + 1)) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if ("," === c) + break; + if (i === str.length) + break; + } + p.nsp = str.substring(start, i); + } + else { + p.nsp = "/"; + } + // look up id + const next = str.charAt(i + 1); + if ("" !== next && Number(next) == next) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if (null == c || Number(c) != c) { + --i; + break; + } + if (i === str.length) + break; + } + p.id = Number(str.substring(start, i + 1)); + } + // look up json data + if (str.charAt(++i)) { + const payload = this.tryParse(str.substr(i)); + if (Decoder.isPayloadValid(p.type, payload)) { + p.data = payload; + } + else { + throw new Error("invalid payload"); + } + } + debug("decoded %s as %j", str, p); + return p; + } + tryParse(str) { + try { + return JSON.parse(str, this.reviver); + } + catch (e) { + return false; + } + } + static isPayloadValid(type, payload) { + switch (type) { + case PacketType.CONNECT: + return typeof payload === "object"; + case PacketType.DISCONNECT: + return payload === undefined; + case PacketType.CONNECT_ERROR: + return typeof payload === "string" || typeof payload === "object"; + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + return Array.isArray(payload) && payload.length > 0; + case PacketType.ACK: + case PacketType.BINARY_ACK: + return Array.isArray(payload); + } + } + /** + * Deallocates a parser's resources + */ + destroy() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } + } +} +exports.Decoder = Decoder; +/** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + */ +class BinaryReconstructor { + constructor(packet) { + this.packet = packet; + this.buffers = []; + this.reconPack = packet; + } + /** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + */ + takeBinaryData(binData) { + this.buffers.push(binData); + if (this.buffers.length === this.reconPack.attachments) { + // done with buffer list + const packet = binary_js_1.reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + return null; + } + /** + * Cleans up binary packet reconstruction variables. + */ + finishedReconstruction() { + this.reconPack = null; + this.buffers = []; + } +} diff --git a/node_modules/socket.io-parser/build/cjs/is-binary.js b/node_modules/socket.io-parser/build/cjs/is-binary.js new file mode 100644 index 0000000..4b7c234 --- /dev/null +++ b/node_modules/socket.io-parser/build/cjs/is-binary.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasBinary = exports.isBinary = void 0; +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const isView = (obj) => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj.buffer instanceof ArrayBuffer; +}; +const toString = Object.prototype.toString; +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + toString.call(Blob) === "[object BlobConstructor]"); +const withNativeFile = typeof File === "function" || + (typeof File !== "undefined" && + toString.call(File) === "[object FileConstructor]"); +/** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ +function isBinary(obj) { + return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) || + (withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File)); +} +exports.isBinary = isBinary; +function hasBinary(obj, toJSON) { + if (!obj || typeof obj !== "object") { + return false; + } + if (Array.isArray(obj)) { + for (let i = 0, l = obj.length; i < l; i++) { + if (hasBinary(obj[i])) { + return true; + } + } + return false; + } + if (isBinary(obj)) { + return true; + } + if (obj.toJSON && + typeof obj.toJSON === "function" && + arguments.length === 1) { + return hasBinary(obj.toJSON(), true); + } + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + return true; + } + } + return false; +} +exports.hasBinary = hasBinary; diff --git a/node_modules/socket.io-parser/build/cjs/package.json b/node_modules/socket.io-parser/build/cjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/socket.io-parser/build/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/socket.io-parser/build/esm-debug/binary.d.ts b/node_modules/socket.io-parser/build/esm-debug/binary.d.ts new file mode 100644 index 0000000..835bd62 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/binary.d.ts @@ -0,0 +1,20 @@ +/** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ +export declare function deconstructPacket(packet: any): { + packet: any; + buffers: any[]; +}; +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ +export declare function reconstructPacket(packet: any, buffers: any): any; diff --git a/node_modules/socket.io-parser/build/esm-debug/binary.js b/node_modules/socket.io-parser/build/esm-debug/binary.js new file mode 100644 index 0000000..dc715d7 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/binary.js @@ -0,0 +1,83 @@ +import { isBinary } from "./is-binary.js"; +/** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ +export function deconstructPacket(packet) { + const buffers = []; + const packetData = packet.data; + const pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + return { packet: pack, buffers: buffers }; +} +function _deconstructPacket(data, buffers) { + if (!data) + return data; + if (isBinary(data)) { + const placeholder = { _placeholder: true, num: buffers.length }; + buffers.push(data); + return placeholder; + } + else if (Array.isArray(data)) { + const newData = new Array(data.length); + for (let i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + return newData; + } + else if (typeof data === "object" && !(data instanceof Date)) { + const newData = {}; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + newData[key] = _deconstructPacket(data[key], buffers); + } + } + return newData; + } + return data; +} +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ +export function reconstructPacket(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + return packet; +} +function _reconstructPacket(data, buffers) { + if (!data) + return data; + if (data && data._placeholder === true) { + const isIndexValid = typeof data.num === "number" && + data.num >= 0 && + data.num < buffers.length; + if (isIndexValid) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } + else { + throw new Error("illegal attachments"); + } + } + else if (Array.isArray(data)) { + for (let i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } + else if (typeof data === "object") { + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + } + return data; +} diff --git a/node_modules/socket.io-parser/build/esm-debug/index.d.ts b/node_modules/socket.io-parser/build/esm-debug/index.d.ts new file mode 100644 index 0000000..3a20f9d --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/index.d.ts @@ -0,0 +1,90 @@ +import { Emitter } from "@socket.io/component-emitter"; +/** + * Protocol version. + * + * @public + */ +export declare const protocol: number; +export declare enum PacketType { + CONNECT = 0, + DISCONNECT = 1, + EVENT = 2, + ACK = 3, + CONNECT_ERROR = 4, + BINARY_EVENT = 5, + BINARY_ACK = 6 +} +export interface Packet { + type: PacketType; + nsp: string; + data?: any; + id?: number; + attachments?: number; +} +/** + * A socket.io Encoder instance + */ +export declare class Encoder { + private replacer?; + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(replacer?: (this: any, key: string, value: any) => any); + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + encode(obj: Packet): any[]; + /** + * Encode packet as string. + */ + private encodeAsString; + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + private encodeAsBinary; +} +interface DecoderReservedEvents { + decoded: (packet: Packet) => void; +} +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ +export declare class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { + private reviver?; + private reconstructor; + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(reviver?: (this: any, key: string, value: any) => any); + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + add(obj: any): void; + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + private decodeString; + private tryParse; + private static isPayloadValid; + /** + * Deallocates a parser's resources + */ + destroy(): void; +} +export {}; diff --git a/node_modules/socket.io-parser/build/esm-debug/index.js b/node_modules/socket.io-parser/build/esm-debug/index.js new file mode 100644 index 0000000..f085981 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/index.js @@ -0,0 +1,293 @@ +import { Emitter } from "@socket.io/component-emitter"; +import { deconstructPacket, reconstructPacket } from "./binary.js"; +import { isBinary, hasBinary } from "./is-binary.js"; +import debugModule from "debug"; // debug() +const debug = debugModule("socket.io-parser"); // debug() +/** + * Protocol version. + * + * @public + */ +export const protocol = 5; +export var PacketType; +(function (PacketType) { + PacketType[PacketType["CONNECT"] = 0] = "CONNECT"; + PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT"; + PacketType[PacketType["EVENT"] = 2] = "EVENT"; + PacketType[PacketType["ACK"] = 3] = "ACK"; + PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR"; + PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT"; + PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK"; +})(PacketType || (PacketType = {})); +/** + * A socket.io Encoder instance + */ +export class Encoder { + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(replacer) { + this.replacer = replacer; + } + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + encode(obj) { + debug("encoding packet %j", obj); + if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) { + if (hasBinary(obj)) { + obj.type = + obj.type === PacketType.EVENT + ? PacketType.BINARY_EVENT + : PacketType.BINARY_ACK; + return this.encodeAsBinary(obj); + } + } + return [this.encodeAsString(obj)]; + } + /** + * Encode packet as string. + */ + encodeAsString(obj) { + // first is type + let str = "" + obj.type; + // attachments if we have them + if (obj.type === PacketType.BINARY_EVENT || + obj.type === PacketType.BINARY_ACK) { + str += obj.attachments + "-"; + } + // if we have a namespace other than `/` + // we append it followed by a comma `,` + if (obj.nsp && "/" !== obj.nsp) { + str += obj.nsp + ","; + } + // immediately followed by the id + if (null != obj.id) { + str += obj.id; + } + // json data + if (null != obj.data) { + str += JSON.stringify(obj.data, this.replacer); + } + debug("encoded %j as %s", obj, str); + return str; + } + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + encodeAsBinary(obj) { + const deconstruction = deconstructPacket(obj); + const pack = this.encodeAsString(deconstruction.packet); + const buffers = deconstruction.buffers; + buffers.unshift(pack); // add packet info to beginning of data list + return buffers; // write all the buffers + } +} +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ +export class Decoder extends Emitter { + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(reviver) { + super(); + this.reviver = reviver; + } + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + add(obj) { + let packet; + if (typeof obj === "string") { + if (this.reconstructor) { + throw new Error("got plaintext data when reconstructing a packet"); + } + packet = this.decodeString(obj); + if (packet.type === PacketType.BINARY_EVENT || + packet.type === PacketType.BINARY_ACK) { + // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); + // no attachments, labeled binary but no binary data to follow + if (packet.attachments === 0) { + super.emitReserved("decoded", packet); + } + } + else { + // non-binary full packet + super.emitReserved("decoded", packet); + } + } + else if (isBinary(obj) || obj.base64) { + // raw binary data + if (!this.reconstructor) { + throw new Error("got binary data when not reconstructing a packet"); + } + else { + packet = this.reconstructor.takeBinaryData(obj); + if (packet) { + // received final buffer + this.reconstructor = null; + super.emitReserved("decoded", packet); + } + } + } + else { + throw new Error("Unknown type: " + obj); + } + } + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + decodeString(str) { + let i = 0; + // look up type + const p = { + type: Number(str.charAt(0)), + }; + if (PacketType[p.type] === undefined) { + throw new Error("unknown packet type " + p.type); + } + // look up attachments if type binary + if (p.type === PacketType.BINARY_EVENT || + p.type === PacketType.BINARY_ACK) { + const start = i + 1; + while (str.charAt(++i) !== "-" && i != str.length) { } + const buf = str.substring(start, i); + if (buf != Number(buf) || str.charAt(i) !== "-") { + throw new Error("Illegal attachments"); + } + p.attachments = Number(buf); + } + // look up namespace (if any) + if ("/" === str.charAt(i + 1)) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if ("," === c) + break; + if (i === str.length) + break; + } + p.nsp = str.substring(start, i); + } + else { + p.nsp = "/"; + } + // look up id + const next = str.charAt(i + 1); + if ("" !== next && Number(next) == next) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if (null == c || Number(c) != c) { + --i; + break; + } + if (i === str.length) + break; + } + p.id = Number(str.substring(start, i + 1)); + } + // look up json data + if (str.charAt(++i)) { + const payload = this.tryParse(str.substr(i)); + if (Decoder.isPayloadValid(p.type, payload)) { + p.data = payload; + } + else { + throw new Error("invalid payload"); + } + } + debug("decoded %s as %j", str, p); + return p; + } + tryParse(str) { + try { + return JSON.parse(str, this.reviver); + } + catch (e) { + return false; + } + } + static isPayloadValid(type, payload) { + switch (type) { + case PacketType.CONNECT: + return typeof payload === "object"; + case PacketType.DISCONNECT: + return payload === undefined; + case PacketType.CONNECT_ERROR: + return typeof payload === "string" || typeof payload === "object"; + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + return Array.isArray(payload) && payload.length > 0; + case PacketType.ACK: + case PacketType.BINARY_ACK: + return Array.isArray(payload); + } + } + /** + * Deallocates a parser's resources + */ + destroy() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } + } +} +/** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + */ +class BinaryReconstructor { + constructor(packet) { + this.packet = packet; + this.buffers = []; + this.reconPack = packet; + } + /** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + */ + takeBinaryData(binData) { + this.buffers.push(binData); + if (this.buffers.length === this.reconPack.attachments) { + // done with buffer list + const packet = reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + return null; + } + /** + * Cleans up binary packet reconstruction variables. + */ + finishedReconstruction() { + this.reconPack = null; + this.buffers = []; + } +} diff --git a/node_modules/socket.io-parser/build/esm-debug/is-binary.d.ts b/node_modules/socket.io-parser/build/esm-debug/is-binary.d.ts new file mode 100644 index 0000000..fa18261 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/is-binary.d.ts @@ -0,0 +1,7 @@ +/** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ +export declare function isBinary(obj: any): boolean; +export declare function hasBinary(obj: any, toJSON?: boolean): any; diff --git a/node_modules/socket.io-parser/build/esm-debug/is-binary.js b/node_modules/socket.io-parser/build/esm-debug/is-binary.js new file mode 100644 index 0000000..0c654dd --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/is-binary.js @@ -0,0 +1,50 @@ +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const isView = (obj) => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj.buffer instanceof ArrayBuffer; +}; +const toString = Object.prototype.toString; +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + toString.call(Blob) === "[object BlobConstructor]"); +const withNativeFile = typeof File === "function" || + (typeof File !== "undefined" && + toString.call(File) === "[object FileConstructor]"); +/** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ +export function isBinary(obj) { + return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) || + (withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File)); +} +export function hasBinary(obj, toJSON) { + if (!obj || typeof obj !== "object") { + return false; + } + if (Array.isArray(obj)) { + for (let i = 0, l = obj.length; i < l; i++) { + if (hasBinary(obj[i])) { + return true; + } + } + return false; + } + if (isBinary(obj)) { + return true; + } + if (obj.toJSON && + typeof obj.toJSON === "function" && + arguments.length === 1) { + return hasBinary(obj.toJSON(), true); + } + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + return true; + } + } + return false; +} diff --git a/node_modules/socket.io-parser/build/esm-debug/package.json b/node_modules/socket.io-parser/build/esm-debug/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/socket.io-parser/build/esm-debug/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/socket.io-parser/build/esm/binary.d.ts b/node_modules/socket.io-parser/build/esm/binary.d.ts new file mode 100644 index 0000000..835bd62 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/binary.d.ts @@ -0,0 +1,20 @@ +/** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ +export declare function deconstructPacket(packet: any): { + packet: any; + buffers: any[]; +}; +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ +export declare function reconstructPacket(packet: any, buffers: any): any; diff --git a/node_modules/socket.io-parser/build/esm/binary.js b/node_modules/socket.io-parser/build/esm/binary.js new file mode 100644 index 0000000..dc715d7 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/binary.js @@ -0,0 +1,83 @@ +import { isBinary } from "./is-binary.js"; +/** + * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @public + */ +export function deconstructPacket(packet) { + const buffers = []; + const packetData = packet.data; + const pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + return { packet: pack, buffers: buffers }; +} +function _deconstructPacket(data, buffers) { + if (!data) + return data; + if (isBinary(data)) { + const placeholder = { _placeholder: true, num: buffers.length }; + buffers.push(data); + return placeholder; + } + else if (Array.isArray(data)) { + const newData = new Array(data.length); + for (let i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + return newData; + } + else if (typeof data === "object" && !(data instanceof Date)) { + const newData = {}; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + newData[key] = _deconstructPacket(data[key], buffers); + } + } + return newData; + } + return data; +} +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @public + */ +export function reconstructPacket(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + return packet; +} +function _reconstructPacket(data, buffers) { + if (!data) + return data; + if (data && data._placeholder === true) { + const isIndexValid = typeof data.num === "number" && + data.num >= 0 && + data.num < buffers.length; + if (isIndexValid) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } + else { + throw new Error("illegal attachments"); + } + } + else if (Array.isArray(data)) { + for (let i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } + else if (typeof data === "object") { + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + } + return data; +} diff --git a/node_modules/socket.io-parser/build/esm/index.d.ts b/node_modules/socket.io-parser/build/esm/index.d.ts new file mode 100644 index 0000000..3a20f9d --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/index.d.ts @@ -0,0 +1,90 @@ +import { Emitter } from "@socket.io/component-emitter"; +/** + * Protocol version. + * + * @public + */ +export declare const protocol: number; +export declare enum PacketType { + CONNECT = 0, + DISCONNECT = 1, + EVENT = 2, + ACK = 3, + CONNECT_ERROR = 4, + BINARY_EVENT = 5, + BINARY_ACK = 6 +} +export interface Packet { + type: PacketType; + nsp: string; + data?: any; + id?: number; + attachments?: number; +} +/** + * A socket.io Encoder instance + */ +export declare class Encoder { + private replacer?; + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(replacer?: (this: any, key: string, value: any) => any); + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + encode(obj: Packet): any[]; + /** + * Encode packet as string. + */ + private encodeAsString; + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + private encodeAsBinary; +} +interface DecoderReservedEvents { + decoded: (packet: Packet) => void; +} +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ +export declare class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { + private reviver?; + private reconstructor; + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(reviver?: (this: any, key: string, value: any) => any); + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + add(obj: any): void; + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + private decodeString; + private tryParse; + private static isPayloadValid; + /** + * Deallocates a parser's resources + */ + destroy(): void; +} +export {}; diff --git a/node_modules/socket.io-parser/build/esm/index.js b/node_modules/socket.io-parser/build/esm/index.js new file mode 100644 index 0000000..fca8aa1 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/index.js @@ -0,0 +1,288 @@ +import { Emitter } from "@socket.io/component-emitter"; +import { deconstructPacket, reconstructPacket } from "./binary.js"; +import { isBinary, hasBinary } from "./is-binary.js"; +/** + * Protocol version. + * + * @public + */ +export const protocol = 5; +export var PacketType; +(function (PacketType) { + PacketType[PacketType["CONNECT"] = 0] = "CONNECT"; + PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT"; + PacketType[PacketType["EVENT"] = 2] = "EVENT"; + PacketType[PacketType["ACK"] = 3] = "ACK"; + PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR"; + PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT"; + PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK"; +})(PacketType || (PacketType = {})); +/** + * A socket.io Encoder instance + */ +export class Encoder { + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(replacer) { + this.replacer = replacer; + } + /** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + */ + encode(obj) { + if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) { + if (hasBinary(obj)) { + obj.type = + obj.type === PacketType.EVENT + ? PacketType.BINARY_EVENT + : PacketType.BINARY_ACK; + return this.encodeAsBinary(obj); + } + } + return [this.encodeAsString(obj)]; + } + /** + * Encode packet as string. + */ + encodeAsString(obj) { + // first is type + let str = "" + obj.type; + // attachments if we have them + if (obj.type === PacketType.BINARY_EVENT || + obj.type === PacketType.BINARY_ACK) { + str += obj.attachments + "-"; + } + // if we have a namespace other than `/` + // we append it followed by a comma `,` + if (obj.nsp && "/" !== obj.nsp) { + str += obj.nsp + ","; + } + // immediately followed by the id + if (null != obj.id) { + str += obj.id; + } + // json data + if (null != obj.data) { + str += JSON.stringify(obj.data, this.replacer); + } + return str; + } + /** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + */ + encodeAsBinary(obj) { + const deconstruction = deconstructPacket(obj); + const pack = this.encodeAsString(deconstruction.packet); + const buffers = deconstruction.buffers; + buffers.unshift(pack); // add packet info to beginning of data list + return buffers; // write all the buffers + } +} +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + */ +export class Decoder extends Emitter { + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(reviver) { + super(); + this.reviver = reviver; + } + /** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + */ + add(obj) { + let packet; + if (typeof obj === "string") { + if (this.reconstructor) { + throw new Error("got plaintext data when reconstructing a packet"); + } + packet = this.decodeString(obj); + if (packet.type === PacketType.BINARY_EVENT || + packet.type === PacketType.BINARY_ACK) { + // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); + // no attachments, labeled binary but no binary data to follow + if (packet.attachments === 0) { + super.emitReserved("decoded", packet); + } + } + else { + // non-binary full packet + super.emitReserved("decoded", packet); + } + } + else if (isBinary(obj) || obj.base64) { + // raw binary data + if (!this.reconstructor) { + throw new Error("got binary data when not reconstructing a packet"); + } + else { + packet = this.reconstructor.takeBinaryData(obj); + if (packet) { + // received final buffer + this.reconstructor = null; + super.emitReserved("decoded", packet); + } + } + } + else { + throw new Error("Unknown type: " + obj); + } + } + /** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + */ + decodeString(str) { + let i = 0; + // look up type + const p = { + type: Number(str.charAt(0)), + }; + if (PacketType[p.type] === undefined) { + throw new Error("unknown packet type " + p.type); + } + // look up attachments if type binary + if (p.type === PacketType.BINARY_EVENT || + p.type === PacketType.BINARY_ACK) { + const start = i + 1; + while (str.charAt(++i) !== "-" && i != str.length) { } + const buf = str.substring(start, i); + if (buf != Number(buf) || str.charAt(i) !== "-") { + throw new Error("Illegal attachments"); + } + p.attachments = Number(buf); + } + // look up namespace (if any) + if ("/" === str.charAt(i + 1)) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if ("," === c) + break; + if (i === str.length) + break; + } + p.nsp = str.substring(start, i); + } + else { + p.nsp = "/"; + } + // look up id + const next = str.charAt(i + 1); + if ("" !== next && Number(next) == next) { + const start = i + 1; + while (++i) { + const c = str.charAt(i); + if (null == c || Number(c) != c) { + --i; + break; + } + if (i === str.length) + break; + } + p.id = Number(str.substring(start, i + 1)); + } + // look up json data + if (str.charAt(++i)) { + const payload = this.tryParse(str.substr(i)); + if (Decoder.isPayloadValid(p.type, payload)) { + p.data = payload; + } + else { + throw new Error("invalid payload"); + } + } + return p; + } + tryParse(str) { + try { + return JSON.parse(str, this.reviver); + } + catch (e) { + return false; + } + } + static isPayloadValid(type, payload) { + switch (type) { + case PacketType.CONNECT: + return typeof payload === "object"; + case PacketType.DISCONNECT: + return payload === undefined; + case PacketType.CONNECT_ERROR: + return typeof payload === "string" || typeof payload === "object"; + case PacketType.EVENT: + case PacketType.BINARY_EVENT: + return Array.isArray(payload) && payload.length > 0; + case PacketType.ACK: + case PacketType.BINARY_ACK: + return Array.isArray(payload); + } + } + /** + * Deallocates a parser's resources + */ + destroy() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } + } +} +/** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + */ +class BinaryReconstructor { + constructor(packet) { + this.packet = packet; + this.buffers = []; + this.reconPack = packet; + } + /** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + */ + takeBinaryData(binData) { + this.buffers.push(binData); + if (this.buffers.length === this.reconPack.attachments) { + // done with buffer list + const packet = reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + return null; + } + /** + * Cleans up binary packet reconstruction variables. + */ + finishedReconstruction() { + this.reconPack = null; + this.buffers = []; + } +} diff --git a/node_modules/socket.io-parser/build/esm/is-binary.d.ts b/node_modules/socket.io-parser/build/esm/is-binary.d.ts new file mode 100644 index 0000000..fa18261 --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/is-binary.d.ts @@ -0,0 +1,7 @@ +/** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ +export declare function isBinary(obj: any): boolean; +export declare function hasBinary(obj: any, toJSON?: boolean): any; diff --git a/node_modules/socket.io-parser/build/esm/is-binary.js b/node_modules/socket.io-parser/build/esm/is-binary.js new file mode 100644 index 0000000..0c654dd --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/is-binary.js @@ -0,0 +1,50 @@ +const withNativeArrayBuffer = typeof ArrayBuffer === "function"; +const isView = (obj) => { + return typeof ArrayBuffer.isView === "function" + ? ArrayBuffer.isView(obj) + : obj.buffer instanceof ArrayBuffer; +}; +const toString = Object.prototype.toString; +const withNativeBlob = typeof Blob === "function" || + (typeof Blob !== "undefined" && + toString.call(Blob) === "[object BlobConstructor]"); +const withNativeFile = typeof File === "function" || + (typeof File !== "undefined" && + toString.call(File) === "[object FileConstructor]"); +/** + * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. + * + * @private + */ +export function isBinary(obj) { + return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) || + (withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File)); +} +export function hasBinary(obj, toJSON) { + if (!obj || typeof obj !== "object") { + return false; + } + if (Array.isArray(obj)) { + for (let i = 0, l = obj.length; i < l; i++) { + if (hasBinary(obj[i])) { + return true; + } + } + return false; + } + if (isBinary(obj)) { + return true; + } + if (obj.toJSON && + typeof obj.toJSON === "function" && + arguments.length === 1) { + return hasBinary(obj.toJSON(), true); + } + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + return true; + } + } + return false; +} diff --git a/node_modules/socket.io-parser/build/esm/package.json b/node_modules/socket.io-parser/build/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/socket.io-parser/build/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/socket.io-parser/package.json b/node_modules/socket.io-parser/package.json new file mode 100644 index 0000000..0d83dc1 --- /dev/null +++ b/node_modules/socket.io-parser/package.json @@ -0,0 +1,55 @@ +{ + "name": "socket.io-parser", + "version": "4.2.1", + "description": "socket.io protocol parser", + "repository": { + "type": "git", + "url": "https://github.com/socketio/socket.io-parser.git" + }, + "files": [ + "build/" + ], + "main": "./build/cjs/index.js", + "module": "./build/esm/index.js", + "types": "./build/esm/index.d.ts", + "exports": { + "import": { + "node": "./build/esm-debug/index.js", + "default": "./build/esm/index.js" + }, + "require": "./build/cjs/index.js" + }, + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "devDependencies": { + "@babel/core": "~7.9.6", + "@babel/preset-env": "~7.9.6", + "@types/debug": "^4.1.5", + "@types/node": "^14.11.1", + "babelify": "~10.0.0", + "benchmark": "2.1.2", + "expect.js": "0.3.1", + "mocha": "3.2.0", + "prettier": "^2.1.2", + "rimraf": "^3.0.2", + "socket.io-browsers": "^1.0.0", + "typescript": "^4.0.3", + "zuul": "3.11.1", + "zuul-ngrok": "4.0.0" + }, + "scripts": { + "compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh", + "test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi", + "test:node": "mocha --reporter dot --bail test/index.js", + "test:browser": "zuul test/index.js --no-coverage", + "format:fix": "prettier --write --parser typescript 'lib/**/*.ts' 'test/**/*.js'", + "format:check": "prettier --check --parser typescript 'lib/**/*.ts' 'test/**/*.js'", + "prepack": "npm run compile" + }, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } +} diff --git a/node_modules/web-streams-polyfill/LICENSE b/node_modules/web-streams-polyfill/LICENSE new file mode 100644 index 0000000..4ca5166 --- /dev/null +++ b/node_modules/web-streams-polyfill/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2020 Mattias Buelens +Copyright (c) 2016 Diwank Singh Tomer + +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/node_modules/web-streams-polyfill/README.md b/node_modules/web-streams-polyfill/README.md new file mode 100644 index 0000000..7056882 --- /dev/null +++ b/node_modules/web-streams-polyfill/README.md @@ -0,0 +1,114 @@ +# web-streams-polyfill + +Web Streams, based on the WHATWG spec reference implementation. + +[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill) +[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill) +[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE) +[![Join the chat at https://gitter.im/web-streams-polyfill/Lobby](https://badges.gitter.im/web-streams-polyfill/Lobby.svg)](https://gitter.im/web-streams-polyfill/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## Links + + - [Official spec][spec] + - [Reference implementation][ref-impl] + +## Usage + +This library comes in multiple variants: +* `web-streams-polyfill`: a polyfill that replaces the native stream implementations. + Recommended for use in web apps supporting older browsers through a ` + + + +``` +Usage as a Node module: +```js +var streams = require("web-streams-polyfill/ponyfill"); +var readable = new streams.ReadableStream(); +``` +Usage as a ES2015 module: +```js +import { ReadableStream } from "web-streams-polyfill/ponyfill"; +const readable = new ReadableStream(); +``` + +### Compatibility + +The `polyfill` and `ponyfill` variants work in any ES5-compatible environment that has a global `Promise`. +If you need to support older browsers or Node versions that do not have a native `Promise` implementation +(check the [support table][promise-support]), you must first include a `Promise` polyfill +(e.g. [promise-polyfill][promise-polyfill]). + +The `polyfill/es6` and `ponyfill/es6` variants work in any ES2015-compatible environment. + +The `polyfill/es2018` and `ponyfill/es2018` variants work in any ES2018-compatible environment. + +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`. + +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill]. + +### Compliance + +The polyfill implements [version `4b6b93c` (25 Oct 2021)][spec-snapshot] of the streams specification. + +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations. +The polyfill aims to pass all tests, although it allows some exceptions for practical reasons: +* The `es2018` variant passes all of the tests, except for the ["bad buffers and views" tests for readable byte streams][wpt-bad-buffers]. + These tests require the implementation to synchronously transfer the contents of an `ArrayBuffer`, which is not yet possible from JavaScript (although there is a [proposal][proposal-arraybuffer-transfer] to make it possible). + The reference implementation "cheats" on these tests [by making a copy instead][ref-impl-transferarraybuffer], but that is unacceptable for the polyfill's performance ([#3][issue-3]). +* The `es6` variant passes the same tests as the `es2018` variant, except for the [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype]. + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018. + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype. +* The `es5` variant passes the same tests as the `es6` variant, except for various tests about specific characteristics of the constructors, properties and methods. + These test failures do not affect the run-time behavior of the polyfill. + For example: + * The `name` property of down-leveled constructors is incorrect. + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect. + * Not all properties and methods are correctly marked as non-enumerable. + * Down-leveled class methods are not correctly marked as non-constructable. + +The type definitions are compatible with the built-in stream types of TypeScript 3.3. + +### Contributors + +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]: + + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr)) + - Anders Riutta ([ariutta](https://github.com/ariutta)) + +[spec]: https://streams.spec.whatwg.org +[ref-impl]: https://github.com/whatwg/streams +[ponyfill]: https://github.com/sindresorhus/ponyfill +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/4b6b93c69e531e2fe45a6ed4cb1484a7ba4eb8bb/ +[wpt]: https://github.com/web-platform-tests/wpt/tree/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams +[wpt-bad-buffers]: https://github.com/web-platform-tests/wpt/blob/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams/readable-byte-streams/bad-buffers-and-views.any.js +[proposal-arraybuffer-transfer]: https://github.com/domenic/proposal-arraybuffer-transfer +[ref-impl-transferarraybuffer]: https://github.com/whatwg/streams/blob/4b6b93c69e531e2fe45a6ed4cb1484a7ba4eb8bb/reference-implementation/lib/abstract-ops/ecmascript.js#L16 +[issue-3]: https://github.com/MattiasBuelens/web-streams-polyfill/issues/3 +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/96ca25f0f7526282c0d47e6bf6a7edd439da1968/streams/readable-streams/async-iterator.any.js#L24 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v2.0.0/src/target/es5/stub/async-iterator-prototype.ts +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.js b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js new file mode 100644 index 0000000..4e26968 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js @@ -0,0 +1,4241 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=polyfill.es2018.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map new file mode 100644 index 0000000..1f9d92a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException","exports"],"mappings":";;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,WAAW,IAAI,UAAU,WAAW,GAAoB;;ICL5D;aAEgB,IAAI;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,SAAS,UAAU;QACjB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,OAAO,IAAI,CAAC;SACb;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAEM,MAAM,OAAO,GAAG,UAAU,EAAE;;aCdnB,YAAY,CAAC,CAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI;;ICbV,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IACrE,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;aAEnD,UAAU,CAAI,QAGrB;QACP,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;IACvC,CA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BAA+B;QAC/B,4BAA4B;QAC5B,yBAAyB;QACzB,2BAA2B;QAC3B,wBAAwB;QAExB,cAAc;QACd,+BAA+B;QAC/B,2BAA2B;QAE3B,yBAAyB;QACzB,oBAAoB;QAEpB,eAAe;QACf,gCAAgC;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,KAAK,MAAM,IAAI,IAAIA,SAAO,EAAE;YAC1B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;gBACvD,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;oBACnC,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;oBAC9C,QAAQ,EAAE,IAAI;oBACd,YAAY,EAAE,IAAI;iBACnB,CAAC,CAAC;aACJ;SACF;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js new file mode 100644 index 0000000..725d242 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}const o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}const a=r,i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,a)}function _(e,t){h(e,t)}function m(e,t){h(e,void 0,t)}function p(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,a)}const g=(()=>{const e=o&&o.queueMicrotask;if("function"==typeof e)return e;const t=d(void 0);return e=>b(t,e)})();function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function v(e,t,r){try{return d(S(e,t,r))}catch(e){return f(e)}}class w{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function R(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?q(e):"closed"===t._state?function(e){q(e),O(e)}(e):E(e,t._storedError)}function T(e,t){return br(e._ownerReadableStream,t)}function C(e){"readable"===e._ownerReadableStream._state?W(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){E(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function E(e,t){q(e),W(e,t)}function W(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function O(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const B=t("[[AbortSteps]]"),k=t("[[ErrorSteps]]"),j=t("[[CancelSteps]]"),A=t("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function L(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function F(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function I(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function N(e,t){if(!dr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}get closed(){return J(this)?this._closedPromise:f(Z("closed"))}cancel(e){return J(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Z("cancel"))}read(){if(!J(this))return f(Z("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw Z("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function J(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[A](t)}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const ee=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return f(P("iterate"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,g((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){const r=T(t,e);return C(t),p(r,(()=>({value:e,done:!0})))}return C(t),d({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():f(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):f(ne("return"))}};function oe(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ee&&Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};function ie(e){return e.slice()}function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}function ue(e){const t=se(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ce(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function de(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function fe(e){e._queue=new w,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!he(this))throw De("view");return this._view}respond(e){if(!he(this))throw De("respond");if($(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!he(this))throw De("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Ae(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!be(this))throw Le("byobRequest");return Be(this)}get desiredSize(){if(!be(this))throw Le("desiredSize");return ke(this)}close(){if(!be(this))throw Le("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ee(this)}enqueue(e){if(!be(this))throw Le("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);We(this,e)}error(e){if(!be(this))throw Le("error");Oe(this,e)}[j](e){me(this),fe(this);const t=this._cancelAlgorithm(e);return qe(this),t}[A](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,we(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),_e(this)}}function be(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function he(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function _e(e){if(!function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(Me(t)&&$e(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e))}),(t=>{Oe(e,t)}))}function me(e){Re(e),e._pendingPullIntos=new w}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=ye(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function ye(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ge(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Se(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function we(e){0===e._queueTotalSize&&e._closeRequested?(qe(e),hr(e._controlledReadableByteStream)):_e(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Se(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){const r=e._controlledReadableByteStream;if(Me(r))for(;$e(r)>0;)pe(r,Pe(e))}(e):function(e,t,r){if(ve(0,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=se(r.buffer,t-o,t);ge(e,n,0,n.byteLength)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),Te(e)}(e,t,r),_e(e)}function Pe(e){return e._pendingPullIntos.shift()}function qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Oe(e,t),t}}qe(e),hr(t)}}function We(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,t.buffer=t.buffer}if(Re(e),X(r))if(0===G(r))ge(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);U(r,new Uint8Array(i,n,a),!1)}else Me(r)?(ge(e,i,n,a),Te(e)):ge(e,i,n,a);_e(e)}function Oe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(me(e),fe(e),qe(e),_r(r,t))}function Be(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}function Ae(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}function ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,fe(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new w,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,_e(t)}),(e=>{Oe(t,e)}))}function De(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Le(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Fe(e){return new ReadableStreamBYOBReader(e)}function Ie(e,t){e._reader._readIntoRequests.push(t)}function $e(e){return e._reader._readIntoRequests.length}function Me(e){const t=e._reader;return void 0!==t&&!!Qe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!be(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}get closed(){return Qe(this)?this._closedPromise:f(xe("closed"))}cancel(e){return Qe(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(xe("cancel"))}read(e){if(!Qe(this))return f(xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return Ye(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Qe(this))throw xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function Qe(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ye(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Ie(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(Se(e,l)){const t=ye(l);return we(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Oe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),Ie(o,r),_e(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}function xe(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Ne(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function He(e){const{size:t}=e;return t||(()=>1)}function Ve(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ue(o,`${t} has member 'size' that`)}}function Ue(e,t){return F(e,t),t=>Q(e(t))}function Ge(e,t,r){return F(e,r),r=>v(e,t,[r])}function Xe(e,t,r){return F(e,r),()=>v(e,t,[])}function Je(e,t,r){return F(e,r),r=>S(e,t,[r])}function Ke(e,t,r){return F(e,r),(r,o)=>v(e,t,[r,o])}function Ze(e,t){if(!ot(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const et="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){L(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ge(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:Xe(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Je(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ke(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");rt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=He(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0),s=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(i=e=>t.write(e,n));void 0!==t.close&&(l=()=>t.close());void 0!==t.abort&&(s=e=>t.abort(e));vt(e,n,a,i,l,s,r,o)}(this,o,Ne(r,1),n)}get locked(){if(!ot(this))throw Et("locked");return nt(this)}abort(e){return ot(this)?nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):at(this,e):f(Et("abort"))}close(){return ot(this)?nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):ct(this)?f(new TypeError("Cannot close an already-closing stream")):it(this):f(Et("close"))}getWriter(){if(!ot(this))throw Et("getWriter");return tt(this)}}function tt(e){return new WritableStreamDefaultWriter(e)}function rt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ot(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function nt(e){return void 0!==e._writer}function at(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort();const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||st(e,t),a}function it(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&$t(o),de(n=e._writableStreamController,gt,0),Tt(n),r}function lt(e,t){"writable"!==e._state?ut(e):st(e,t)}function st(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&mt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&ut(e)}function ut(e){e._state="errored",e._writableStreamController[k]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new w,void 0===e._pendingAbortRequest)return void dt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void dt(e);h(e._writableStreamController[B](r._reason),(()=>{r._resolve(),dt(e)}),(t=>{r._reject(t),dt(e)}))}function ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function dt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&At(t,e._storedError)}function ft(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Dt(e)}(r):$t(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),Ze(e,"First parameter"),nt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ct(e)&&e._backpressure?Dt(this):Ft(this),kt(this);else if("erroring"===t)Lt(this,e._storedError),kt(this);else if("closed"===t)Ft(this),kt(r=this),zt(r);else{const t=e._storedError;Lt(this,t),jt(this,t)}var r}get closed(){return bt(this)?this._closedPromise:f(Ot("closed"))}get desiredSize(){if(!bt(this))throw Ot("desiredSize");if(void 0===this._ownerWritableStream)throw Bt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Rt(t._writableStreamController)}(this)}get ready(){return bt(this)?this._readyPromise:f(Ot("ready"))}abort(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("abort")):function(e,t){return at(e._ownerWritableStream,t)}(this,e):f(Ot("abort"))}close(){if(!bt(this))return f(Ot("close"));const e=this._ownerWritableStream;return void 0===e?f(Bt("close")):ct(e)?f(new TypeError("Cannot close an already-closing stream")):ht(this)}releaseLock(){if(!bt(this))throw Ot("releaseLock");void 0!==this._ownerWritableStream&&pt(this)}write(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("write to")):yt(this,e):f(Ot("write"))}}function bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function ht(e){return it(e._ownerWritableStream)}function _t(e,t){"pending"===e._closedPromiseState?At(e,t):function(e,t){jt(e,t)}(e,t)}function mt(e,t){"pending"===e._readyPromiseState?It(e,t):function(e,t){Lt(e,t)}(e,t)}function pt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");mt(e,r),_t(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function yt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Ct(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(Bt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ct(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{de(e,t,r)}catch(t){return void Ct(e,t)}const o=e._controlledWritableStream;if(!ct(o)&&"writable"===o._state){ft(o,Pt(e))}Tt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const gt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!St(this))throw Wt("abortReason");return this._abortReason}get signal(){if(!St(this))throw Wt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!St(this))throw Wt("error");"writable"===this._controlledWritableStream._state&&qt(this,e)}[B](e){const t=this._abortAlgorithm(e);return wt(this),t}[k](){fe(this)}}function St(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function vt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._abortReason=void 0,t._abortController=function(){if(et)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Pt(t);ft(e,s);h(d(r()),(()=>{t._started=!0,Tt(t)}),(r=>{t._started=!0,lt(e,r)}))}function wt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Rt(e){return e._strategyHWM-e._queueTotalSize}function Tt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void ut(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===gt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ce(e);const r=e._closeAlgorithm();wt(e),h(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&zt(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),lt(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ce(e),!ct(r)&&"writable"===t){const t=Pt(e);ft(r,t)}Tt(e)}),(t=>{"writable"===r._state&&wt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,lt(e,t)}(r,t)}))}(e,r)}function Ct(e,t){"writable"===e._controlledWritableStream._state&&qt(e,t)}function Pt(e){return Rt(e)<=0}function qt(e,t){const r=e._controlledWritableStream;wt(e),st(r,t)}function Et(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Wt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Ot(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Bt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function kt(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function jt(e,t){kt(e),At(e,t)}function At(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function zt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Dt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Lt(e,t){Dt(e),It(e,t)}function Ft(e){Dt(e),$t(e)}function It(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function $t(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Mt="undefined"!=typeof DOMException?DOMException:void 0;const Qt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Mt)?Mt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function Yt(e,t,o,n,a,i){const l=H(e),s=tt(t);e._disturbed=!0;let u=!1,p=d(void 0);return c(((g,S)=>{let v;if(void 0!==i){if(v=()=>{const r=new Qt("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?at(t,r):d(void 0))),a||o.push((()=>"readable"===e._state?br(e,r):d(void 0))),E((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(q(e,l._closedPromise,(e=>{n?W(!0,e):E((()=>at(t,e)),!0,e)})),q(t,s._closedPromise,(t=>{a?W(!0,t):E((()=>br(e,t)),!0,t)})),w=e,R=l._closedPromise,T=()=>{o?W():E((()=>function(e){const t=e._ownerWritableStream,r=t._state;return ct(t)||"closed"===r?d(void 0):"errored"===r?f(t._storedError):ht(e)}(s)))},"closed"===w._state?T():_(R,T),ct(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):E((()=>br(e,t)),!0,t)}function P(){const e=p;return b(p,(()=>e!==p?P():void 0))}function q(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function E(e,r,o){function n(){h(e(),(()=>O(r,o)),(e=>O(!0,e)))}u||(u=!0,"writable"!==t._state||ct(t)?n():_(P(),n))}function W(e,r){u||(u=!0,"writable"!==t._state||ct(t)?O(e,r):_(P(),(()=>O(e,r))))}function O(e,t){pt(s),C(l),void 0!==i&&i.removeEventListener("abort",v),e?S(t):g(void 0)}y(c(((e,t)=>{!function o(n){n?e():b(u?d(!0):b(s._readyPromise,(()=>c(((e,t)=>{K(l,{_chunkSteps:t=>{p=b(yt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!xt(this))throw er("desiredSize");return Jt(this)}close(){if(!xt(this))throw er("close");if(!Kt(this))throw new TypeError("The stream is not in a state that permits close");Ut(this)}enqueue(e){if(!xt(this))throw er("enqueue");if(!Kt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Gt(this,e)}error(e){if(!xt(this))throw er("error");Xt(this,e)}[j](e){fe(this);const t=this._cancelAlgorithm(e);return Vt(this),t}[A](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ce(this);this._closeRequested&&0===this._queue.length?(Vt(this),hr(t)):Nt(this),e._chunkSteps(r)}else V(t,e),Nt(this)}}function xt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function Nt(e){if(!Ht(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nt(e))}),(t=>{Xt(e,t)}))}function Ht(e){const t=e._controlledReadableStream;if(!Kt(e))return!1;if(!e._started)return!1;if(fr(t)&&G(t)>0)return!0;return Jt(e)>0}function Vt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ut(e){if(!Kt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Vt(e),hr(t))}function Gt(e,t){if(!Kt(e))return;const r=e._controlledReadableStream;if(fr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Xt(e,t),t}try{de(e,t,r)}catch(t){throw Xt(e,t),t}}Nt(e)}function Xt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(fe(e),Vt(e),_r(r,t))}function Jt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Kt(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Zt(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,Nt(t)}),(e=>{Xt(t,e)}))}function er(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function tr(e,t){return be(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{a=e}));function _(e){m(e._closedPromise,(t=>{e===i&&(Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),f&&b||a(void 0))}))}function p(){Qe(i)&&(C(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{g((()=>{s=!1,u=!1;const r=t;let i=t;if(!f&&!b)try{i=ue(t)}catch(t){return Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),void a(br(e,t))}f||We(o._readableStreamController,r),b||We(n._readableStreamController,i),l=!1,s?S():u&&v()}))},_closeSteps:()=>{l=!1,f||Ee(o._readableStreamController),b||Ee(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function y(t,r){J(i)&&(C(i),i=Fe(e),_(i));const c=r?n:o,d=r?o:n;Ye(i,t,{_chunkSteps:t=>{g((()=>{s=!1,u=!1;const o=r?b:f;if(r?f:b)o||Ae(c._readableStreamController,t);else{let r;try{r=ue(t)}catch(t){return Oe(c._readableStreamController,t),Oe(d._readableStreamController,t),void a(br(e,t))}o||Ae(c._readableStreamController,t),We(d._readableStreamController,r)}l=!1,s?S():u&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ee(c._readableStreamController),o||Ee(d._readableStreamController),void 0!==e&&(t||Ae(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&je(d._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function S(){if(l)return s=!0,d(void 0);l=!0;const e=Be(o._readableStreamController);return null===e?p():y(e._view,!1),d(void 0)}function v(){if(l)return u=!0,d(void 0);l=!0;const e=Be(n._readableStreamController);return null===e?p():y(e._view,!0),d(void 0)}function w(o){if(f=!0,t=o,b){const o=ie([t,r]),n=br(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ie([t,r]),n=br(e,o);a(n)}return h}function T(){}return o=ur(T,S,w),n=ur(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{l=e}));function _(){if(s)return u=!0,d(void 0);s=!0;return K(r,{_chunkSteps:e=>{g((()=>{u=!1;const t=e,r=e;f||Gt(a._readableStreamController,t),b||Gt(i._readableStreamController,r),s=!1,u&&_()}))},_closeSteps:()=>{s=!1,f||Ut(a._readableStreamController),b||Ut(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),d(void 0)}function p(t){if(f=!0,o=t,b){const t=ie([o,n]),r=br(e,t);l(r)}return h}function y(t){if(b=!0,n=t,f){const t=ie([o,n]),r=br(e,t);l(r)}return h}function S(){}return a=sr(S,_,p),i=sr(S,_,y),m(r._closedPromise,(e=>{Xt(a._readableStreamController,e),Xt(i._readableStreamController,e),f&&b||l(void 0)})),[a,i]}(e)}function rr(e,t,r){return F(e,r),r=>v(e,t,[r])}function or(e,t,r){return F(e,r),r=>v(e,t,[r])}function nr(e,t,r){return F(e,r),r=>S(e,t,[r])}function ar(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function ir(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function lr(e,t){L(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){L(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:or(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:nr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:ar(l,`${t} has member 'type' that`)}}(e,"First parameter");if(cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n=()=>{},a=()=>d(void 0),i=()=>d(void 0);void 0!==t.start&&(n=()=>t.start(o)),void 0!==t.pull&&(a=()=>t.pull(o)),void 0!==t.cancel&&(i=e=>t.cancel(e));const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");ze(e,o,n,a,i,r,l)}(this,o,Ne(r,0))}else{const e=He(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(i=()=>t.pull(n)),void 0!==t.cancel&&(l=e=>t.cancel(e)),Zt(e,n,a,i,l,r,o)}(this,o,Ne(r,1),e)}}get locked(){if(!dr(this))throw mr("locked");return fr(this)}cancel(e){return dr(this)?fr(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):br(this,e):f(mr("cancel"))}getReader(e){if(!dr(this))throw mr("getReader");return void 0===function(e,t){L(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:ir(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):Fe(this)}pipeThrough(e,t={}){if(!dr(this))throw mr("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){L(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),Ze(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=lr(t,"Second parameter");if(fr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(nt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Yt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!dr(this))return f(mr("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!ot(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=lr(t,"Second parameter")}catch(e){return f(e)}return fr(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):nt(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Yt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!dr(this))throw mr("tee");return ie(tr(this))}values(e){if(!dr(this))throw mr("values");return function(e,t){const r=H(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){L(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function sr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);cr(a);return Zt(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function ur(e,t,r){const o=Object.create(ReadableStream.prototype);cr(o);return ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function dr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function fr(e){return void 0!==e._reader}function br(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);hr(e);const o=e._reader;void 0!==o&&Qe(o)&&(o._readIntoRequests.forEach((e=>{e._closeSteps(void 0)})),o._readIntoRequests=new w);return p(e._readableStreamController[j](t),r)}function hr(e){e._state="closed";const t=e._reader;void 0!==t&&(O(t),J(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new w))}function _r(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(W(r,t),J(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new w):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new w))}function mr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function pr(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const yr=e=>e.byteLength;try{Object.defineProperty(yr,"name",{value:"size",configurable:!0})}catch(e){}class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=pr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Sr(this))throw gr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Sr(this))throw gr("size");return yr}}function gr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Sr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const vr=()=>1;try{Object.defineProperty(vr,"name",{value:"size",configurable:!0})}catch(e){}class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=pr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Rr(this))throw wr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Rr(this))throw wr("size");return vr}}function wr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Rr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Tr(e,t,r){return F(e,r),r=>v(e,t,[r])}function Cr(e,t,r){return F(e,r),r=>S(e,t,[r])}function Pr(e,t,r){return F(e,r),(r,o)=>v(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ve(t,"Second parameter"),n=Ve(r,"Third parameter"),a=function(e,t){L(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Tr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:Cr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:Pr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Ne(n,0),l=He(n),s=Ne(o,1),u=He(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Ar(r,t)}))}return Ar(r,t)}(e,t)}function s(t){return function(e,t){return Er(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,o=r._flushAlgorithm();return kr(r),p(o,(()=>{if("errored"===t._state)throw t._storedError;Ut(t._readableStreamController)}),(r=>{throw Er(e,r),t._storedError}))}(e)}function c(){return function(e){return Or(e,!1),e._backpressureChangePromise}(e)}function f(t){return Wr(e,t),d(void 0)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return rt(i),vt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,u,s,r,o),e._readable=sr(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Or(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o=e=>{try{return jr(r,e),d(void 0)}catch(e){return f(e)}},n=()=>d(void 0);void 0!==t.transform&&(o=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!qr(this))throw Dr("readable");return this._readable}get writable(){if(!qr(this))throw Dr("writable");return this._writable}}function qr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Er(e,t){Xt(e._readable._readableStreamController,t),Wr(e,t)}function Wr(e,t){kr(e._transformStreamController),Ct(e._writable._writableStreamController,t),e._backpressure&&Or(e,!1)}function Or(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Br(this))throw zr("desiredSize");return Jt(this._controlledTransformStream._readable._readableStreamController)}enqueue(e){if(!Br(this))throw zr("enqueue");jr(this,e)}error(e){if(!Br(this))throw zr("error");var t;t=e,Er(this._controlledTransformStream,t)}terminate(){if(!Br(this))throw zr("terminate");!function(e){const t=e._controlledTransformStream;Ut(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Wr(t,r)}(this)}}function Br(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function kr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function jr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!Kt(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{Gt(o,t)}catch(e){throw Wr(r,e),r._readable._storedError}(function(e){return!Ht(e)})(o)!==r._backpressure&&Or(r,!0)}function Ar(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw Er(e._controlledTransformStream,t),t}))}function zr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Dr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Lr={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==o)for(const e in Lr)Object.prototype.hasOwnProperty.call(Lr,e)&&Object.defineProperty(o,e,{value:Lr[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=polyfill.es2018.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map new file mode 100644 index 0000000..b27333d --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.min.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","globals","self","window","global","typeIsObject","x","rethrowAssertionErrorRejection","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseResolve","resolve","bind","originalPromiseReject","reject","newPromise","executor","promiseResolvedWith","value","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","fn","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","[object Object]","this","_front","_elements","_next","_back","_cursor","_size","length","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","push","oldFront","newFront","oldCursor","newCursor","elements","callback","i","node","front","cursor","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","name","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","shift","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","Object","hasOwnProperty","_disturbed","_readableStreamController","defineProperties","cancel","enumerable","read","releaseLock","toStringTag","defineProperty","configurable","AsyncIteratorPrototype","getPrototypeOf","async","ReadableStreamAsyncIteratorImpl","preventCancel","_preventCancel","nextSteps","_nextSteps","_ongoingPromise","returnSteps","_returnSteps","_isFinished","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","next","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","ArrayBufferSlice","buffer","begin","end","ArrayBuffer","CloneAsUint8Array","O","byteOffset","byteLength","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","isView","ReadableByteStreamControllerRespondWithNewView","respond","respondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","ReadableByteStreamControllerEnqueue","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","controller","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","min","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","ready","queue","headOfQueue","peek","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInternal","firstDescriptor","ReadableByteStreamControllerRespondInClosedState","remainderSize","remainder","ReadableByteStreamControllerRespondInReadableState","transferredBuffer","firstPendingPullInto","ReadableStreamError","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","close","enqueue","error","byobReaderBrandCheckException","ReadableStreamBYOBReaderRead","constructor","DataView","BYTES_PER_ELEMENT","ctor","emptyView","ReadableByteStreamControllerPullInto","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","forEach","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","getWriter","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createDOMExceptionPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","cloneE","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","clonedChunk","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","mode","convertPipeOptions","options","isAbortSignal","assertAbortSignal","Boolean","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","rawOptions","convertReaderOptions","rawTransform","transform","readable","convertReadableWritablePair","destination","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","getReader","pipeThrough","pipeTo","tee","values","asyncIterator","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","IsTransformStreamDefaultController","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","terminate","exports","prop"],"mappings":"0PAEA,MAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACAE,GAAe,UAAUA,cCHbC,KAeT,MAAMC,EAVS,oBAATC,KACFA,KACoB,oBAAXC,OACTA,OACoB,oBAAXC,OACTA,YADF,WCROC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,EAGlD,MAAMC,EAUPP,ECbAQ,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAyBJ,QAAQK,QAAQC,KAAKP,GAC9CQ,EAAwBP,QAAQQ,OAAOF,KAAKP,YAElCU,EAAcC,GAI5B,OAAO,IAAIX,EAAgBW,YAGbC,EAAuBC,GACrC,OAAOR,EAAuBQ,YAGhBC,EAA+BC,GAC7C,OAAOP,EAAsBO,YAGfC,EACdC,EACAC,EACAC,GAGA,OAAOjB,EAAoBkB,KAAKH,EAASC,EAAaC,YAGxCE,EACdJ,EACAC,EACAC,GACAH,EACEA,EAAmBC,EAASC,EAAaC,QACzCG,EACAvB,YAIYwB,EAAmBN,EAAqBC,GACtDG,EAAYJ,EAASC,YAGPM,EAAcP,EAA2BE,GACvDE,EAAYJ,OAASK,EAAWH,YAGlBM,EACdR,EACAS,EACAC,GACA,OAAOX,EAAmBC,EAASS,EAAoBC,YAGz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aAChBT,OAAOU,eAAemd,iCAAiCtmB,UAAWd,EAAOgK,YAAa,CACpFxI,MAAO,mCACP0I,cAAc,IC7TlB,MAAMie,GAAU,CACdzF,eAAAA,eACA5D,gCAAAA,gCACA5Q,6BAAAA,6BACAZ,0BAAAA,0BACApF,4BAAAA,4BACAoL,yBAAAA,yBAEA8B,eAAAA,eACAW,gCAAAA,gCACAa,4BAAAA,4BAEAyN,0BAAAA,0BACAK,qBAAAA,qBAEAO,gBAAAA,gBACAmC,iCAAAA,kCAIF,QAAuB,IAAZhnB,EACT,IAAK,MAAMgoB,KAAQD,GACb5e,OAAOzI,UAAU0I,eAAezH,KAAKomB,GAASC,IAChD7e,OAAOU,eAAe7J,EAASgoB,EAAM,CACnC5mB,MAAO2mB,GAAQC,GACftL,UAAU,EACV5S,cAAc"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs new file mode 100644 index 0000000..b764c06 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs @@ -0,0 +1,4219 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseResolve = Promise.resolve.bind(originalPromise); +const originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } +} +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es2018.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map new file mode 100644 index 0000000..c6449f6 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","streamB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QAAQ,CAAC,yBAA+D,CAAC,CAAC;KAChH,EAAE,CAAC;QACF,oBAAoB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAChC,MAAM,QAAQ,CAAC,YAAY,CAAC;KAC7B,CAAC,CAAC;AACL,CAAC;AAED;AAEA,SAAS,yCAAyC,CAAC,MAAuB;;IAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;IAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;AAC3C,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY;IACxD,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,yDAAyD,CAAC,CAAC;AACjH,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY;IAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;AAC/E;;ACzfA,MAAM,OAAO,GAAG;IACd,cAAc;IACd,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;IAC3B,wBAAwB;IAExB,cAAc;IACd,+BAA+B;IAC/B,2BAA2B;IAE3B,yBAAyB;IACzB,oBAAoB;IAEpB,eAAe;IACf,gCAAgC;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;QAC1B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;YACvD,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;gBACnC,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;gBAC9C,QAAQ,EAAE,IAAI;gBACd,YAAY,EAAE,IAAI;aACnB,CAAC,CAAC;SACJ;KACF;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.js b/node_modules/web-streams-polyfill/dist/polyfill.es6.js new file mode 100644 index 0000000..18a4721 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.js @@ -0,0 +1,4252 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + let AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=polyfill.es6.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map new file mode 100644 index 0000000..ac2d583 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException","exports"],"mappings":";;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,WAAW,IAAI,UAAU,WAAW,GAAoB;;ICL5D;aAEgB,IAAI;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,SAAS,UAAU;QACjB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,OAAO,IAAI,CAAC;SACb;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAEM,MAAM,OAAO,GAAG,UAAU,EAAE;;aCdnB,YAAY,CAAC,CAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI;;ICbV,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAA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AAM,EAAE,KAAK,CAAC,CAAC;;QAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;IAC3C,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY;QACxD,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,yDAAyD,CAAC,CAAC;IACjH,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY;QAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;IAC/E;;ICzfA,MAAMI,SAAO,GAAG;QACd,cAAc;QACd,+BAA+B;QAC/B,4BAA4B;QAC5B,yBAAyB;QACzB,2BAA2B;QAC3B,wBAAwB;QAExB,cAAc;QACd,+BAA+B;QAC/B,2BAA2B;QAE3B,yBAAyB;QACzB,oBAAoB;QAEpB,eAAe;QACf,gCAAgC;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,KAAK,MAAM,IAAI,IAAIA,SAAO,EAAE;YAC1B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;gBACvD,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;oBACnC,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;oBAC9C,QAAQ,EAAE,IAAI;oBACd,YAAY,EAAE,IAAI;iBACnB,CAAC,CAAC;aACJ;SACF;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js new file mode 100644 index 0000000..c711d89 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}const o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}const a=r,i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,a)}function _(e,t){h(e,t)}function m(e,t){h(e,void 0,t)}function p(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,a)}const S=(()=>{const e=o&&o.queueMicrotask;if("function"==typeof e)return e;const t=d(void 0);return e=>b(t,e)})();function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function v(e,t,r){try{return d(g(e,t,r))}catch(e){return f(e)}}class w{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function R(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?q(e):"closed"===t._state?function(e){q(e),O(e)}(e):E(e,t._storedError)}function T(e,t){return br(e._ownerReadableStream,t)}function C(e){"readable"===e._ownerReadableStream._state?W(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){E(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function E(e,t){q(e),W(e,t)}function W(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function O(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const B=t("[[AbortSteps]]"),k=t("[[ErrorSteps]]"),j=t("[[CancelSteps]]"),A=t("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function L(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function F(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function Y(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Y(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Y(D(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function N(e,t){if(!dr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}get closed(){return J(this)?this._closedPromise:f(Z("closed"))}cancel(e){return J(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Z("cancel"))}read(){if(!J(this))return f(Z("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw Z("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function J(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[A](t)}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let ee;Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof t.asyncIterator&&(ee={[t.asyncIterator](){return this}},Object.defineProperty(ee,t.asyncIterator,{enumerable:!1}));class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return f(P("iterate"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,S((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){const r=T(t,e);return C(t),p(r,(()=>({value:e,done:!0})))}return C(t),d({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():f(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):f(ne("return"))}};function oe(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ee&&Object.setPrototypeOf(re,ee);const ae=Number.isNaN||function(e){return e!=e};function ie(e){return e.slice()}function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}function ue(e){const t=se(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ce(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function de(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function fe(e){e._queue=new w,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!he(this))throw De("view");return this._view}respond(e){if(!he(this))throw De("respond");if($(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!he(this))throw De("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Ae(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!be(this))throw Ie("byobRequest");return Be(this)}get desiredSize(){if(!be(this))throw Ie("desiredSize");return ke(this)}close(){if(!be(this))throw Ie("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ee(this)}enqueue(e){if(!be(this))throw Ie("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);We(this,e)}error(e){if(!be(this))throw Ie("error");Oe(this,e)}[j](e){me(this),fe(this);const t=this._cancelAlgorithm(e);return qe(this),t}[A](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,we(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),_e(this)}}function be(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function he(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function _e(e){if(!function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(Me(t)&&$e(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,_e(e))}),(t=>{Oe(e,t)}))}function me(e){Re(e),e._pendingPullIntos=new w}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=ye(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function ye(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Se(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ge(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function we(e){0===e._queueTotalSize&&e._closeRequested?(qe(e),hr(e._controlledReadableByteStream)):_e(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ge(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){const r=e._controlledReadableByteStream;if(Me(r))for(;$e(r)>0;)pe(r,Pe(e))}(e):function(e,t,r){if(ve(0,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=se(r.buffer,t-o,t);Se(e,n,0,n.byteLength)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),Te(e)}(e,t,r),_e(e)}function Pe(e){return e._pendingPullIntos.shift()}function qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Oe(e,t),t}}qe(e),hr(t)}}function We(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,t.buffer=t.buffer}if(Re(e),X(r))if(0===G(r))Se(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);U(r,new Uint8Array(i,n,a),!1)}else Me(r)?(Se(e,i,n,a),Te(e)):Se(e,i,n,a);_e(e)}function Oe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(me(e),fe(e),qe(e),_r(r,t))}function Be(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}function Ae(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}function ze(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,fe(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new w,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,_e(t)}),(e=>{Oe(t,e)}))}function De(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ie(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Le(e){return new ReadableStreamBYOBReader(e)}function Fe(e,t){e._reader._readIntoRequests.push(t)}function $e(e){return e._reader._readIntoRequests.length}function Me(e){const t=e._reader;return void 0!==t&&!!Qe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),fr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!be(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}get closed(){return Qe(this)?this._closedPromise:f(xe("closed"))}cancel(e){return Qe(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(xe("cancel"))}read(e){if(!Qe(this))return f(xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return Ye(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Qe(this))throw xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}}}function Qe(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ye(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void Fe(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(ge(e,l)){const t=ye(l);return we(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Oe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),Fe(o,r),_e(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}function xe(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Ne(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function He(e){const{size:t}=e;return t||(()=>1)}function Ve(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ue(o,`${t} has member 'size' that`)}}function Ue(e,t){return L(e,t),t=>Q(e(t))}function Ge(e,t,r){return L(e,r),r=>v(e,t,[r])}function Xe(e,t,r){return L(e,r),()=>v(e,t,[])}function Je(e,t,r){return L(e,r),r=>g(e,t,[r])}function Ke(e,t,r){return L(e,r),(r,o)=>v(e,t,[r,o])}function Ze(e,t){if(!ot(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const et="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){I(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ge(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:Xe(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Je(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ke(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");rt(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=He(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0),s=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(i=e=>t.write(e,n));void 0!==t.close&&(l=()=>t.close());void 0!==t.abort&&(s=e=>t.abort(e));vt(e,n,a,i,l,s,r,o)}(this,o,Ne(r,1),n)}get locked(){if(!ot(this))throw Et("locked");return nt(this)}abort(e){return ot(this)?nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):at(this,e):f(Et("abort"))}close(){return ot(this)?nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):ct(this)?f(new TypeError("Cannot close an already-closing stream")):it(this):f(Et("close"))}getWriter(){if(!ot(this))throw Et("getWriter");return tt(this)}}function tt(e){return new WritableStreamDefaultWriter(e)}function rt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ot(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function nt(e){return void 0!==e._writer}function at(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort();const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||st(e,t),a}function it(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&$t(o),de(n=e._writableStreamController,St,0),Tt(n),r}function lt(e,t){"writable"!==e._state?ut(e):st(e,t)}function st(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&mt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&ut(e)}function ut(e){e._state="errored",e._writableStreamController[k]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new w,void 0===e._pendingAbortRequest)return void dt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void dt(e);h(e._writableStreamController[B](r._reason),(()=>{r._resolve(),dt(e)}),(t=>{r._reject(t),dt(e)}))}function ct(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function dt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&At(t,e._storedError)}function ft(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Dt(e)}(r):$t(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),Ze(e,"First parameter"),nt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ct(e)&&e._backpressure?Dt(this):Lt(this),kt(this);else if("erroring"===t)It(this,e._storedError),kt(this);else if("closed"===t)Lt(this),kt(r=this),zt(r);else{const t=e._storedError;It(this,t),jt(this,t)}var r}get closed(){return bt(this)?this._closedPromise:f(Ot("closed"))}get desiredSize(){if(!bt(this))throw Ot("desiredSize");if(void 0===this._ownerWritableStream)throw Bt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Rt(t._writableStreamController)}(this)}get ready(){return bt(this)?this._readyPromise:f(Ot("ready"))}abort(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("abort")):function(e,t){return at(e._ownerWritableStream,t)}(this,e):f(Ot("abort"))}close(){if(!bt(this))return f(Ot("close"));const e=this._ownerWritableStream;return void 0===e?f(Bt("close")):ct(e)?f(new TypeError("Cannot close an already-closing stream")):ht(this)}releaseLock(){if(!bt(this))throw Ot("releaseLock");void 0!==this._ownerWritableStream&&pt(this)}write(e){return bt(this)?void 0===this._ownerWritableStream?f(Bt("write to")):yt(this,e):f(Ot("write"))}}function bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function ht(e){return it(e._ownerWritableStream)}function _t(e,t){"pending"===e._closedPromiseState?At(e,t):function(e,t){jt(e,t)}(e,t)}function mt(e,t){"pending"===e._readyPromiseState?Ft(e,t):function(e,t){It(e,t)}(e,t)}function pt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");mt(e,r),_t(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function yt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Ct(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(Bt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ct(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{de(e,t,r)}catch(t){return void Ct(e,t)}const o=e._controlledWritableStream;if(!ct(o)&&"writable"===o._state){ft(o,Pt(e))}Tt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const St={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!gt(this))throw Wt("abortReason");return this._abortReason}get signal(){if(!gt(this))throw Wt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!gt(this))throw Wt("error");"writable"===this._controlledWritableStream._state&&qt(this,e)}[B](e){const t=this._abortAlgorithm(e);return wt(this),t}[k](){fe(this)}}function gt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function vt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._abortReason=void 0,t._abortController=function(){if(et)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Pt(t);ft(e,s);h(d(r()),(()=>{t._started=!0,Tt(t)}),(r=>{t._started=!0,lt(e,r)}))}function wt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Rt(e){return e._strategyHWM-e._queueTotalSize}function Tt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void ut(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===St?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ce(e);const r=e._closeAlgorithm();wt(e),h(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&zt(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),lt(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ce(e),!ct(r)&&"writable"===t){const t=Pt(e);ft(r,t)}Tt(e)}),(t=>{"writable"===r._state&&wt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,lt(e,t)}(r,t)}))}(e,r)}function Ct(e,t){"writable"===e._controlledWritableStream._state&&qt(e,t)}function Pt(e){return Rt(e)<=0}function qt(e,t){const r=e._controlledWritableStream;wt(e),st(r,t)}function Et(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Wt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Ot(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Bt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function kt(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function jt(e,t){kt(e),At(e,t)}function At(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function zt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Dt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function It(e,t){Dt(e),Ft(e,t)}function Lt(e){Dt(e),$t(e)}function Ft(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function $t(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Mt="undefined"!=typeof DOMException?DOMException:void 0;const Qt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Mt)?Mt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function Yt(e,t,o,n,a,i){const l=H(e),s=tt(t);e._disturbed=!0;let u=!1,p=d(void 0);return c(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const r=new Qt("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?at(t,r):d(void 0))),a||o.push((()=>"readable"===e._state?br(e,r):d(void 0))),E((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(q(e,l._closedPromise,(e=>{n?W(!0,e):E((()=>at(t,e)),!0,e)})),q(t,s._closedPromise,(t=>{a?W(!0,t):E((()=>br(e,t)),!0,t)})),w=e,R=l._closedPromise,T=()=>{o?W():E((()=>function(e){const t=e._ownerWritableStream,r=t._state;return ct(t)||"closed"===r?d(void 0):"errored"===r?f(t._storedError):ht(e)}(s)))},"closed"===w._state?T():_(R,T),ct(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,t):E((()=>br(e,t)),!0,t)}function P(){const e=p;return b(p,(()=>e!==p?P():void 0))}function q(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function E(e,r,o){function n(){h(e(),(()=>O(r,o)),(e=>O(!0,e)))}u||(u=!0,"writable"!==t._state||ct(t)?n():_(P(),n))}function W(e,r){u||(u=!0,"writable"!==t._state||ct(t)?O(e,r):_(P(),(()=>O(e,r))))}function O(e,t){pt(s),C(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0)}y(c(((e,t)=>{!function o(n){n?e():b(u?d(!0):b(s._readyPromise,(()=>c(((e,t)=>{K(l,{_chunkSteps:t=>{p=b(yt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!xt(this))throw er("desiredSize");return Jt(this)}close(){if(!xt(this))throw er("close");if(!Kt(this))throw new TypeError("The stream is not in a state that permits close");Ut(this)}enqueue(e){if(!xt(this))throw er("enqueue");if(!Kt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Gt(this,e)}error(e){if(!xt(this))throw er("error");Xt(this,e)}[j](e){fe(this);const t=this._cancelAlgorithm(e);return Vt(this),t}[A](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ce(this);this._closeRequested&&0===this._queue.length?(Vt(this),hr(t)):Nt(this),e._chunkSteps(r)}else V(t,e),Nt(this)}}function xt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function Nt(e){if(!Ht(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nt(e))}),(t=>{Xt(e,t)}))}function Ht(e){const t=e._controlledReadableStream;if(!Kt(e))return!1;if(!e._started)return!1;if(fr(t)&&G(t)>0)return!0;return Jt(e)>0}function Vt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ut(e){if(!Kt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Vt(e),hr(t))}function Gt(e,t){if(!Kt(e))return;const r=e._controlledReadableStream;if(fr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Xt(e,t),t}try{de(e,t,r)}catch(t){throw Xt(e,t),t}}Nt(e)}function Xt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(fe(e),Vt(e),_r(r,t))}function Jt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Kt(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Zt(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,fe(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;h(d(r()),(()=>{t._started=!0,Nt(t)}),(e=>{Xt(t,e)}))}function er(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function tr(e,t){return be(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{a=e}));function _(e){m(e._closedPromise,(t=>{e===i&&(Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),f&&b||a(void 0))}))}function p(){Qe(i)&&(C(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{S((()=>{s=!1,u=!1;const r=t;let i=t;if(!f&&!b)try{i=ue(t)}catch(t){return Oe(o._readableStreamController,t),Oe(n._readableStreamController,t),void a(br(e,t))}f||We(o._readableStreamController,r),b||We(n._readableStreamController,i),l=!1,s?g():u&&v()}))},_closeSteps:()=>{l=!1,f||Ee(o._readableStreamController),b||Ee(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&je(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&je(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function y(t,r){J(i)&&(C(i),i=Le(e),_(i));const c=r?n:o,d=r?o:n;Ye(i,t,{_chunkSteps:t=>{S((()=>{s=!1,u=!1;const o=r?b:f;if(r?f:b)o||Ae(c._readableStreamController,t);else{let r;try{r=ue(t)}catch(t){return Oe(c._readableStreamController,t),Oe(d._readableStreamController,t),void a(br(e,t))}o||Ae(c._readableStreamController,t),We(d._readableStreamController,r)}l=!1,s?g():u&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ee(c._readableStreamController),o||Ee(d._readableStreamController),void 0!==e&&(t||Ae(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&je(d._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return s=!0,d(void 0);l=!0;const e=Be(o._readableStreamController);return null===e?p():y(e._view,!1),d(void 0)}function v(){if(l)return u=!0,d(void 0);l=!0;const e=Be(n._readableStreamController);return null===e?p():y(e._view,!0),d(void 0)}function w(o){if(f=!0,t=o,b){const o=ie([t,r]),n=br(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=ie([t,r]),n=br(e,o);a(n)}return h}function T(){}return o=ur(T,g,w),n=ur(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const h=c((e=>{l=e}));function _(){if(s)return u=!0,d(void 0);s=!0;return K(r,{_chunkSteps:e=>{S((()=>{u=!1;const t=e,r=e;f||Gt(a._readableStreamController,t),b||Gt(i._readableStreamController,r),s=!1,u&&_()}))},_closeSteps:()=>{s=!1,f||Ut(a._readableStreamController),b||Ut(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),d(void 0)}function p(t){if(f=!0,o=t,b){const t=ie([o,n]),r=br(e,t);l(r)}return h}function y(t){if(b=!0,n=t,f){const t=ie([o,n]),r=br(e,t);l(r)}return h}function g(){}return a=sr(g,_,p),i=sr(g,_,y),m(r._closedPromise,(e=>{Xt(a._readableStreamController,e),Xt(i._readableStreamController,e),f&&b||l(void 0)})),[a,i]}(e)}function rr(e,t,r){return L(e,r),r=>v(e,t,[r])}function or(e,t,r){return L(e,r),r=>v(e,t,[r])}function nr(e,t,r){return L(e,r),r=>g(e,t,[r])}function ar(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function ir(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function lr(e,t){I(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=Ve(t,"Second parameter"),o=function(e,t){I(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:rr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:or(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:nr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:ar(l,`${t} has member 'type' that`)}}(e,"First parameter");if(cr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n=()=>{},a=()=>d(void 0),i=()=>d(void 0);void 0!==t.start&&(n=()=>t.start(o)),void 0!==t.pull&&(a=()=>t.pull(o)),void 0!==t.cancel&&(i=e=>t.cancel(e));const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");ze(e,o,n,a,i,r,l)}(this,o,Ne(r,0))}else{const e=He(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a=()=>{},i=()=>d(void 0),l=()=>d(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(i=()=>t.pull(n)),void 0!==t.cancel&&(l=e=>t.cancel(e)),Zt(e,n,a,i,l,r,o)}(this,o,Ne(r,1),e)}}get locked(){if(!dr(this))throw mr("locked");return fr(this)}cancel(e){return dr(this)?fr(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):br(this,e):f(mr("cancel"))}getReader(e){if(!dr(this))throw mr("getReader");return void 0===function(e,t){I(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:ir(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):Le(this)}pipeThrough(e,t={}){if(!dr(this))throw mr("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){I(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),Ze(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=lr(t,"Second parameter");if(fr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(nt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Yt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!dr(this))return f(mr("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!ot(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=lr(t,"Second parameter")}catch(e){return f(e)}return fr(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):nt(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Yt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!dr(this))throw mr("tee");return ie(tr(this))}values(e){if(!dr(this))throw mr("values");return function(e,t){const r=H(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){I(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function sr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);cr(a);return Zt(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function ur(e,t,r){const o=Object.create(ReadableStream.prototype);cr(o);return ze(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function cr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function dr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function fr(e){return void 0!==e._reader}function br(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);hr(e);const o=e._reader;void 0!==o&&Qe(o)&&(o._readIntoRequests.forEach((e=>{e._closeSteps(void 0)})),o._readIntoRequests=new w);return p(e._readableStreamController[j](t),r)}function hr(e){e._state="closed";const t=e._reader;void 0!==t&&(O(t),J(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new w))}function _r(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(W(r,t),J(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new w):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new w))}function mr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function pr(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const yr=e=>e.byteLength;try{Object.defineProperty(yr,"name",{value:"size",configurable:!0})}catch(e){}class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=pr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!gr(this))throw Sr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!gr(this))throw Sr("size");return yr}}function Sr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function gr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const vr=()=>1;try{Object.defineProperty(vr,"name",{value:"size",configurable:!0})}catch(e){}class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=pr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Rr(this))throw wr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Rr(this))throw wr("size");return vr}}function wr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Rr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Tr(e,t,r){return L(e,r),r=>v(e,t,[r])}function Cr(e,t,r){return L(e,r),r=>g(e,t,[r])}function Pr(e,t,r){return L(e,r),(r,o)=>v(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ve(t,"Second parameter"),n=Ve(r,"Third parameter"),a=function(e,t){I(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Tr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:Cr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:Pr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Ne(n,0),l=He(n),s=Ne(o,1),u=He(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Ar(r,t)}))}return Ar(r,t)}(e,t)}function s(t){return function(e,t){return Er(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,o=r._flushAlgorithm();return kr(r),p(o,(()=>{if("errored"===t._state)throw t._storedError;Ut(t._readableStreamController)}),(r=>{throw Er(e,r),t._storedError}))}(e)}function c(){return function(e){return Or(e,!1),e._backpressureChangePromise}(e)}function f(t){return Wr(e,t),d(void 0)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return rt(i),vt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,u,s,r,o),e._readable=sr(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Or(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o=e=>{try{return jr(r,e),d(void 0)}catch(e){return f(e)}},n=()=>d(void 0);void 0!==t.transform&&(o=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!qr(this))throw Dr("readable");return this._readable}get writable(){if(!qr(this))throw Dr("writable");return this._writable}}function qr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Er(e,t){Xt(e._readable._readableStreamController,t),Wr(e,t)}function Wr(e,t){kr(e._transformStreamController),Ct(e._writable._writableStreamController,t),e._backpressure&&Or(e,!1)}function Or(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Br(this))throw zr("desiredSize");return Jt(this._controlledTransformStream._readable._readableStreamController)}enqueue(e){if(!Br(this))throw zr("enqueue");jr(this,e)}error(e){if(!Br(this))throw zr("error");var t;t=e,Er(this._controlledTransformStream,t)}terminate(){if(!Br(this))throw zr("terminate");!function(e){const t=e._controlledTransformStream;Ut(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Wr(t,r)}(this)}}function Br(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function kr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function jr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!Kt(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{Gt(o,t)}catch(e){throw Wr(r,e),r._readable._storedError}(function(e){return!Ht(e)})(o)!==r._backpressure&&Or(r,!0)}function Ar(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw Er(e._controlledTransformStream,t),t}))}function zr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Dr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Ir={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==o)for(const e in Ir)Object.prototype.hasOwnProperty.call(Ir,e)&&Object.defineProperty(o,e,{value:Ir[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=polyfill.es6.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map new file mode 100644 index 0000000..33c6f9c --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.min.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","globals","self","window","global","typeIsObject","x","rethrowAssertionErrorRejection","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseResolve","resolve","bind","originalPromiseReject","reject","newPromise","executor","promiseResolvedWith","value","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","fn","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","[object Object]","this","_front","_elements","_next","_back","_cursor","_size","length","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","push","oldFront","newFront","oldCursor","newCursor","elements","callback","i","node","front","cursor","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","name","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","shift","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","Object","hasOwnProperty","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","cancel","enumerable","read","releaseLock","toStringTag","defineProperty","configurable","asyncIterator","ReadableStreamAsyncIteratorImpl","preventCancel","_preventCancel","nextSteps","_nextSteps","_ongoingPromise","returnSteps","_returnSteps","_isFinished","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","next","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","ArrayBufferSlice","buffer","begin","end","ArrayBuffer","CloneAsUint8Array","O","byteOffset","byteLength","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","isView","ReadableByteStreamControllerRespondWithNewView","respond","respondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","ReadableByteStreamControllerEnqueue","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","controller","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","min","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","ready","queue","headOfQueue","peek","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInternal","firstDescriptor","ReadableByteStreamControllerRespondInClosedState","remainderSize","remainder","ReadableByteStreamControllerRespondInReadableState","transferredBuffer","firstPendingPullInto","ReadableStreamError","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","close","enqueue","error","byobReaderBrandCheckException","ReadableStreamBYOBReaderRead","constructor","DataView","BYTES_PER_ELEMENT","ctor","emptyView","ReadableByteStreamControllerPullInto","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","forEach","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","getWriter","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createDOMExceptionPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","cloneE","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","clonedChunk","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","mode","convertPipeOptions","options","isAbortSignal","assertAbortSignal","Boolean","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","rawOptions","convertReaderOptions","rawTransform","transform","readable","convertReadableWritablePair","destination","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","getReader","pipeThrough","pipeTo","tee","values","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","IsTransformStreamDefaultController","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","terminate","exports","prop"],"mappings":"0PAEA,MAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACAE,GAAe,UAAUA,cCHbC,KAeT,MAAMC,EAVS,oBAATC,KACFA,KACoB,oBAAXC,OACTA,OACoB,oBAAXC,OACTA,YADF,WCROC,EAAaC,GAC3B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AQC,GACfrL,UAAU,EACV1S,cAAc"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs new file mode 100644 index 0000000..a405cd1 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs @@ -0,0 +1,4230 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseResolve = Promise.resolve.bind(originalPromise); +const originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +let AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } +} +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es6.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map new file mode 100644 index 0000000..4eeea29 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}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AA8B,CAAC;gBAC9C,QAAQ,EAAE,IAAI;gBACd,YAAY,EAAE,IAAI;aACnB,CAAC,CAAC;SACJ;KACF;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.js b/node_modules/web-streams-polyfill/dist/polyfill.js new file mode 100644 index 0000000..d985d05 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.js @@ -0,0 +1,4382 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(" + description + ")"; }; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseResolve = Promise.resolve.bind(originalPromise); + var originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var queueMicrotask = (function () { + var globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + var resolvedPromise = promiseResolvedWith(undefined); + return function (fn) { return PerformPromiseThen(resolvedPromise, fn); }; + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(context + " is not an object."); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(context + " is not a function."); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(context + " is not an object."); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter " + position + " is required in '" + context + "'."); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(field + " is required in '" + context + "'."); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(context + " is not a finite number"); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(context + " is outside the accepted range of " + lowerBound + " to " + upperBound + ", inclusive"); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(context + " is not a ReadableStream."); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype." + name + " can only be used on a ReadableStreamDefaultReader"); + } + + /// + var _a; + var AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator." + name + " can only be used on a ReadableSteamAsyncIterator"); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be closed"); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be enqueued to"); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + var entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var elementSize = pullIntoDescriptor.elementSize; + var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + var ctor = view.constructor; + // try { + var buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + var remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer; + var byteOffset = chunk.byteOffset; + var byteLength = chunk.byteLength; + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype." + name + " can only be used on a ReadableStreamBYOBRequest"); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype." + name + " can only be used on a ReadableByteStreamController"); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamBYOBReader.prototype.read = function (view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype." + name + " can only be used on a ReadableStreamBYOBReader"); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, context + " has member 'size' that") + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, context + " has member 'abort' that"), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, context + " has member 'close' that"), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, context + " has member 'start' that"), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, context + " has member 'write' that"), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(context + " is not a WritableStream."); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in " + state + " state) is not in the writable state and cannot be closed")); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype." + name + " can only be used on a WritableStream"); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype." + name + " can only be used on a WritableStreamDefaultController"); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype." + name + " can only be used on a WritableStreamDefaultWriter"); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + var NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + var DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = new DOMException$1('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype." + name + " can only be used on a ReadableStreamDefaultController"); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, context + " has member 'autoAllocateChunkSize' that"), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, context + " has member 'cancel' that"), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, context + " has member 'pull' that"), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, context + " has member 'start' that"), + type: type === undefined ? undefined : convertReadableStreamType(type, context + " has member 'type' that") + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "" + type; + if (type !== 'bytes') { + throw new TypeError(context + " '" + type + "' is not a valid enumeration value for ReadableStreamType"); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, context + " has member 'mode' that") + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "" + mode; + if (mode !== 'byob') { + throw new TypeError(context + " '" + mode + "' is not a valid enumeration value for ReadableStreamReaderMode"); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, context + " has member 'signal' that"); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(context + " is not an AbortSignal."); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, context + " has member 'readable' that"); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, context + " has member 'writable' that"); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype." + name + " can only be used on a ReadableStream"); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype." + name + " can only be used on a ByteLengthQueuingStrategy"); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype." + name + " can only be used on a CountQueuingStrategy"); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, context + " has member 'flush' that"), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, context + " has member 'start' that"), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, context + " has member 'transform' that"), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + var flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + var controller = stream._transformStreamController; + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, function () { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, function (r) { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype." + name + " can only be used on a TransformStreamDefaultController"); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype." + name + " can only be used on a TransformStream"); + } + + var exports$1 = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (var prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=polyfill.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.js.map b/node_modules/web-streams-polyfill/dist/polyfill.js.map new file mode 100644 index 0000000..dfbc396 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException","exports"],"mappings":";;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,YAAU,WAAW,MAAoB,GA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;QAC3B,wBAAwB,0BAAA;QAExB,cAAc,gBAAA;QACd,+BAA+B,iCAAA;QAC/B,2BAA2B,6BAAA;QAE3B,yBAAyB,2BAAA;QACzB,oBAAoB,sBAAA;QAEpB,eAAe,iBAAA;QACf,gCAAgC,kCAAA;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,KAAK,IAAM,IAAI,IAAIA,SAAO,EAAE;YAC1B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;gBACvD,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;oBACnC,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;oBAC9C,QAAQ,EAAE,IAAI;oBACd,YAAY,EAAE,IAAI;iBACnB,CAAC,CAAC;aACJ;SACF;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.min.js b/node_modules/web-streams-polyfill/dist/polyfill.min.js new file mode 100644 index 0000000..98a7694 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.min.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol("+e+")"};function t(){}var o="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function n(e){return"object"==typeof e&&null!==e||"function"==typeof e}var a=t,i=Promise,l=Promise.prototype.then,u=Promise.resolve.bind(i),s=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return u(e)}function f(e){return s(e)}function b(e,r,t){return l.call(e,r,t)}function p(e,r,t){b(b(e,r,t),void 0,a)}function _(e,r){p(e,r)}function h(e,r){p(e,void 0,r)}function m(e,r,t){return b(e,r,t)}function y(e){b(e,void 0,a)}var v=function(){var e=o&&o.queueMicrotask;if("function"==typeof e)return e;var r=d(void 0);return function(e){return b(r,e)}}();function g(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function S(e,r,t){try{return d(g(e,r,t))}catch(e){return f(e)}}var w=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,o=t+1,n=e._elements,a=n[t];return 16384===o&&(r=e._next,o=0),--this._size,this._cursor=o,e!==r&&(this._front=r),n[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,o=t._elements;!(r===o.length&&void 0===t._next||r===o.length&&(r=0,0===(o=(t=t._next)._elements).length));)e(o[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}();function R(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?q(e):"closed"===r._state?function(e){q(e),W(e)}(e):O(e,r._storedError)}function T(e,r){return Tt(e._ownerReadableStream,r)}function C(e){"readable"===e._ownerReadableStream._state?E(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){O(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function O(e,r){q(e),E(e,r)}function E(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function W(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var j=r("[[AbortSteps]]"),B=r("[[ErrorSteps]]"),k=r("[[CancelSteps]]"),A=r("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},D=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError(r+" is not an object.");var t}function F(e,r){if("function"!=typeof e)throw new TypeError(r+" is not a function.")}function L(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(r+" is not an object.")}function M(e,r,t){if(void 0===e)throw new TypeError("Parameter "+r+" is required in '"+t+"'.")}function Q(e,r,t){if(void 0===e)throw new TypeError(r+" is required in '"+t+"'.")}function Y(e){return Number(e)}function x(e){return 0===e?0:e}function N(e,r){var t=Number.MAX_SAFE_INTEGER,o=Number(e);if(o=x(o),!z(o))throw new TypeError(r+" is not a finite number");if((o=function(e){return x(D(e))}(o))<0||o>t)throw new TypeError(r+" is outside the accepted range of 0 to "+t+", inclusive");return z(o)&&0!==o?o:0}function H(e,r){if(!wt(e))throw new TypeError(r+" is not a ReadableStream.")}function V(e){return new $(e)}function U(e,r){e._reader._readRequests.push(r)}function G(e,r,t){var o=e._reader._readRequests.shift();t?o._closeSteps():o._chunkSteps(r)}function X(e){return e._reader._readRequests.length}function J(e){var r=e._reader;return void 0!==r&&!!ee(r)}var K,Z,$=function(){function ReadableStreamDefaultReader(e){if(M(e,1,"ReadableStreamDefaultReader"),H(e,"First parameter"),Rt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");R(this,e),this._readRequests=new w}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ee(this)?this._closedPromise:f(te("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ee(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(te("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ee(this))return f(te("read"));if(void 0===this._ownerReadableStream)return f(P("read from"));var e,r,t=c((function(t,o){e=t,r=o}));return re(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ee(this))throw te("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}},ReadableStreamDefaultReader}();function ee(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof $)}function re(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[A](r)}function te(e){return new TypeError("ReadableStreamDefaultReader.prototype."+e+" can only be used on a ReadableStreamDefaultReader")}Object.defineProperties($.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty($.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof r.asyncIterator&&((K={})[r.asyncIterator]=function(){return this},Z=K,Object.defineProperty(Z,r.asyncIterator,{enumerable:!1}));var oe=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?m(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r,t,o=this._reader;if(void 0===o._ownerReadableStream)return f(P("iterate"));var n=c((function(e,o){r=e,t=o}));return re(o,{_chunkSteps:function(t){e._ongoingPromise=void 0,v((function(){return r({value:t,done:!1})}))},_closeSteps:function(){e._ongoingPromise=void 0,e._isFinished=!0,C(o),r({value:void 0,done:!0})},_errorSteps:function(r){e._ongoingPromise=void 0,e._isFinished=!0,C(o),t(r)}}),n},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(void 0===r._ownerReadableStream)return f(P("finish iterating"));if(!this._preventCancel){var t=T(r,e);return C(r),m(t,(function(){return{value:e,done:!0}}))}return C(r),d({value:e,done:!0})},e}(),ne={next:function(){return ae(this)?this._asyncIteratorImpl.next():f(ie("next"))},return:function(e){return ae(this)?this._asyncIteratorImpl.return(e):f(ie("return"))}};function ae(e){if(!n(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof oe}catch(e){return!1}}function ie(e){return new TypeError("ReadableStreamAsyncIterator."+e+" can only be used on a ReadableSteamAsyncIterator")}void 0!==Z&&Object.setPrototypeOf(ne,Z);var le=Number.isNaN||function(e){return e!=e};function ue(e){return e.slice()}function se(e,r,t,o,n){new Uint8Array(e).set(new Uint8Array(t,o,n),r)}function ce(e,r,t){if(e.slice)return e.slice(r,t);var o=t-r,n=new ArrayBuffer(o);return se(n,0,e,r,o),n}function de(e){var r=ce(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function fe(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function be(e,r,t){if("number"!=typeof(o=t)||le(o)||o<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function pe(e){e._queue=new w,e._queueTotalSize=0}var _e=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!ye(this))throw Me("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!ye(this))throw Me("respond");if(M(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,Ie(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!ye(this))throw Me("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,Fe(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(_e.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(_e.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var he=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!me(this))throw Qe("byobRequest");return ze(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!me(this))throw Qe("desiredSize");return De(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!me(this))throw Qe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");Be(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!me(this))throw Qe("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");ke(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!me(this))throw Qe("error");Ae(this,e)},ReadableByteStreamController.prototype[k]=function(e){ge(this),pe(this);var r=this._cancelAlgorithm(e);return je(this),r},ReadableByteStreamController.prototype[A]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0){var t=this._queue.shift();this._queueTotalSize-=t.byteLength,Pe(this);var o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e._chunkSteps(o)}else{var n=this._autoAllocateChunkSize;if(void 0!==n){var a=void 0;try{a=new ArrayBuffer(n)}catch(r){return void e._errorSteps(r)}var i={buffer:a,bufferByteLength:n,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}U(r,e),ve(this)}},ReadableByteStreamController}();function me(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof he)}function ye(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof _e)}function ve(e){(function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(r)&&X(r)>0)return!0;if(He(r)&&Ne(r)>0)return!0;if(De(e)>0)return!0;return!1})(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ve(e))}),(function(r){Ae(e,r)}))))}function ge(e){qe(e),e._pendingPullIntos=new w}function Se(e,r){var t=!1;"closed"===e._state&&(t=!0);var o=we(r);"default"===r.readerType?G(e,o,t):function(e,r,t){var o=e._reader._readIntoRequests.shift();t?o._closeSteps(r):o._chunkSteps(r)}(e,o,t)}function we(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function Re(e,r,t,o){e._queue.push({buffer:r,byteOffset:t,byteLength:o}),e._queueTotalSize+=o}function Te(e,r){var t=r.elementSize,o=r.bytesFilled-r.bytesFilled%t,n=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),a=r.bytesFilled+n,i=a-a%t,l=n,u=!1;i>o&&(l=i-r.bytesFilled,u=!0);for(var s=e._queue;l>0;){var c=s.peek(),d=Math.min(l,c.byteLength),f=r.byteOffset+r.bytesFilled;se(r.buffer,f,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),e._queueTotalSize-=d,Ce(e,d,r),l-=d}return u}function Ce(e,r,t){t.bytesFilled+=r}function Pe(e){0===e._queueTotalSize&&e._closeRequested?(je(e),Ct(e._controlledReadableByteStream)):ve(e)}function qe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Oe(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Te(e,r)&&(We(e),Se(e._controlledReadableByteStream,r))}}function Ee(e,r){var t=e._pendingPullIntos.peek();qe(e),"closed"===e._controlledReadableByteStream._state?function(e,r){var t=e._controlledReadableByteStream;if(He(t))for(;Ne(t)>0;)Se(t,We(e))}(e):function(e,r,t){if(Ce(0,r,t),!(t.bytesFilled0){var n=t.byteOffset+t.bytesFilled,a=ce(t.buffer,n-o,n);Re(e,a,0,a.byteLength)}t.bytesFilled-=o,Se(e._controlledReadableByteStream,t),Oe(e)}}(e,r,t),ve(e)}function We(e){return e._pendingPullIntos.shift()}function je(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Be(e){var r=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===r._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0)if(e._pendingPullIntos.peek().bytesFilled>0){var t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ae(e,t),t}je(e),Ct(r)}}function ke(e,r){var t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state){var o=r.buffer,n=r.byteOffset,a=r.byteLength,i=o;if(e._pendingPullIntos.length>0){var l=e._pendingPullIntos.peek();l.buffer,0,l.buffer=l.buffer}if(qe(e),J(t))if(0===X(t))Re(e,i,n,a);else e._pendingPullIntos.length>0&&We(e),G(t,new Uint8Array(i,n,a),!1);else He(t)?(Re(e,i,n,a),Oe(e)):Re(e,i,n,a);ve(e)}}function Ae(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(ge(e),pe(e),je(e),Pt(t,r))}function ze(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),o=Object.create(_e.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(o,e,t),e._byobRequest=o}return e._byobRequest}function De(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ie(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=t.buffer,Ee(e,r)}function Fe(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var o=r.byteLength;t.buffer=r.buffer,Ee(e,o)}function Le(e,r,t,o,n,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,pe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=o,r._cancelAlgorithm=n,r._autoAllocateChunkSize=i,r._pendingPullIntos=new w,e._readableStreamController=r,p(d(t()),(function(){r._started=!0,ve(r)}),(function(e){Ae(r,e)}))}function Me(e){return new TypeError("ReadableStreamBYOBRequest.prototype."+e+" can only be used on a ReadableStreamBYOBRequest")}function Qe(e){return new TypeError("ReadableByteStreamController.prototype."+e+" can only be used on a ReadableByteStreamController")}function Ye(e){return new Ve(e)}function xe(e,r){e._reader._readIntoRequests.push(r)}function Ne(e){return e._reader._readIntoRequests.length}function He(e){var r=e._reader;return void 0!==r&&!!Ue(r)}Object.defineProperties(he.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(he.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Ve=function(){function ReadableStreamBYOBReader(e){if(M(e,1,"ReadableStreamBYOBReader"),H(e,"First parameter"),Rt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!me(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");R(this,e),this._readIntoRequests=new w}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return Ue(this)?this._closedPromise:f(Xe("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),Ue(this)?void 0===this._ownerReadableStream?f(P("cancel")):T(this,e):f(Xe("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e){if(!Ue(this))return f(Xe("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(P("read from"));var r,t,o=c((function(e,o){r=e,t=o}));return Ge(this,e,{_chunkSteps:function(e){return r({value:e,done:!1})},_closeSteps:function(e){return r({value:e,done:!0})},_errorSteps:function(e){return t(e)}}),o},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!Ue(this))throw Xe("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");C(this)}},ReadableStreamBYOBReader}();function Ue(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof Ve)}function Ge(e,r,t){var o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?t._errorSteps(o._storedError):function(e,r,t){var o=e._controlledReadableByteStream,n=1;r.constructor!==DataView&&(n=r.constructor.BYTES_PER_ELEMENT);var a=r.constructor,i=r.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void xe(o,t);if("closed"!==o._state){if(e._queueTotalSize>0){if(Te(e,l)){var u=we(l);return Pe(e),void t._chunkSteps(u)}if(e._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ae(e,s),void t._errorSteps(s)}}e._pendingPullIntos.push(l),xe(o,t),ve(e)}else{var c=new a(l.buffer,l.byteOffset,0);t._closeSteps(c)}}(o._readableStreamController,r,t)}function Xe(e){return new TypeError("ReadableStreamBYOBReader.prototype."+e+" can only be used on a ReadableStreamBYOBReader")}function Je(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(le(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function Ke(e){var r=e.size;return r||function(){return 1}}function Ze(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:Y(t),size:void 0===o?void 0:$e(o,r+" has member 'size' that")}}function $e(e,r){return F(e,r),function(r){return Y(e(r))}}function er(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function rr(e,r,t){return F(e,t),function(){return S(e,r,[])}}function tr(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function or(e,r,t){return F(e,t),function(t,o){return S(e,r,[t,o])}}function nr(e,r){if(!sr(e))throw new TypeError(r+" is not a WritableStream.")}Object.defineProperties(Ve.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ve.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var ar="function"==typeof AbortController;var ir=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:L(e,"First parameter");var t=Ze(r,"Second parameter"),o=function(e,r){I(e,r);var t=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:er(t,e,r+" has member 'abort' that"),close:void 0===o?void 0:rr(o,e,r+" has member 'close' that"),start:void 0===n?void 0:tr(n,e,r+" has member 'start' that"),write:void 0===i?void 0:or(i,e,r+" has member 'write' that"),type:a}}(e,"First parameter");if(ur(this),void 0!==o.type)throw new RangeError("Invalid type is specified");var n=Ke(t);!function(e,r,t,o){var n=Object.create(qr.prototype),a=function(){},i=function(){return d(void 0)},l=function(){return d(void 0)},u=function(){return d(void 0)};void 0!==r.start&&(a=function(){return r.start(n)});void 0!==r.write&&(i=function(e){return r.write(e,n)});void 0!==r.close&&(l=function(){return r.close()});void 0!==r.abort&&(u=function(e){return r.abort(e)});Er(e,n,a,i,l,u,t,o)}(this,o,Je(t,1),n)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!sr(this))throw Dr("locked");return cr(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),sr(this)?cr(this)?f(new TypeError("Cannot abort a stream that already has a writer")):dr(this,e):f(Dr("abort"))},WritableStream.prototype.close=function(){return sr(this)?cr(this)?f(new TypeError("Cannot close a stream that already has a writer")):hr(this)?f(new TypeError("Cannot close an already-closing stream")):fr(this):f(Dr("close"))},WritableStream.prototype.getWriter=function(){if(!sr(this))throw Dr("getWriter");return lr(this)},WritableStream}();function lr(e){return new vr(e)}function ur(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new w,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function sr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof ir)}function cr(e){return void 0!==e._writer}function dr(e,r){var t;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort();var o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var n=!1;"erroring"===o&&(n=!0,r=void 0);var a=c((function(t,o){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:o,_reason:r,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||pr(e,r),a}function fr(e){var r=e._state;if("closed"===r||"errored"===r)return f(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));var t,o=c((function(r,t){var o={_resolve:r,_reject:t};e._closeRequest=o})),n=e._writer;return void 0!==n&&e._backpressure&&"writable"===r&&Gr(n),be(t=e._writableStreamController,Pr,0),Br(t),o}function br(e,r){"writable"!==e._state?_r(e):pr(e,r)}function pr(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var o=e._writer;void 0!==o&&Rr(o,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&_r(e)}function _r(e){e._state="errored",e._writableStreamController[B]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new w,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void mr(e);p(e._writableStreamController[j](t._reason),(function(){t._resolve(),mr(e)}),(function(r){t._reject(r),mr(e)}))}else mr(e)}function hr(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function mr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&Yr(r,e._storedError)}function yr(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){Nr(e)}(t):Gr(t)),e._backpressure=r}Object.defineProperties(ir.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(ir.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var vr=function(){function WritableStreamDefaultWriter(e){if(M(e,1,"WritableStreamDefaultWriter"),nr(e,"First parameter"),cr(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!hr(e)&&e._backpressure?Nr(this):Vr(this),Mr(this);else if("erroring"===t)Hr(this,e._storedError),Mr(this);else if("closed"===t)Vr(this),Mr(r=this),xr(r);else{var o=e._storedError;Hr(this,o),Qr(this,o)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return gr(this)?this._closedPromise:f(Fr("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!gr(this))throw Fr("desiredSize");if(void 0===this._ownerWritableStream)throw Lr("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return jr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return gr(this)?this._readyPromise:f(Fr("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),gr(this)?void 0===this._ownerWritableStream?f(Lr("abort")):function(e,r){return dr(e._ownerWritableStream,r)}(this,e):f(Fr("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!gr(this))return f(Fr("close"));var e=this._ownerWritableStream;return void 0===e?f(Lr("close")):hr(e)?f(new TypeError("Cannot close an already-closing stream")):Sr(this)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!gr(this))throw Fr("releaseLock");void 0!==this._ownerWritableStream&&Tr(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),gr(this)?void 0===this._ownerWritableStream?f(Lr("write to")):Cr(this,e):f(Fr("write"))},WritableStreamDefaultWriter}();function gr(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof vr)}function Sr(e){return fr(e._ownerWritableStream)}function wr(e,r){"pending"===e._closedPromiseState?Yr(e,r):function(e,r){Qr(e,r)}(e,r)}function Rr(e,r){"pending"===e._readyPromiseState?Ur(e,r):function(e,r){Hr(e,r)}(e,r)}function Tr(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Rr(e,t),wr(e,t),r._writer=void 0,e._ownerWritableStream=void 0}function Cr(e,r){var t=e._ownerWritableStream,o=t._writableStreamController,n=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return kr(e,r),1}}(o,r);if(t!==e._ownerWritableStream)return f(Lr("write to"));var a=t._state;if("errored"===a)return f(t._storedError);if(hr(t)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(t._storedError);var i=function(e){return c((function(r,t){var o={_resolve:r,_reject:t};e._writeRequests.push(o)}))}(t);return function(e,r,t){try{be(e,r,t)}catch(r){return void kr(e,r)}var o=e._controlledWritableStream;if(!hr(o)&&"writable"===o._state){yr(o,Ar(e))}Br(e)}(o,r,n),i}Object.defineProperties(vr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(vr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Pr={},qr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!Or(this))throw Ir("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!Or(this))throw Ir("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Or(this))throw Ir("error");"writable"===this._controlledWritableStream._state&&zr(this,e)},WritableStreamDefaultController.prototype[j]=function(e){var r=this._abortAlgorithm(e);return Wr(this),r},WritableStreamDefaultController.prototype[B]=function(){pe(this)},WritableStreamDefaultController}();function Or(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof qr)}function Er(e,r,t,o,n,a,i,l){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,pe(r),r._abortReason=void 0,r._abortController=function(){if(ar)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=l,r._strategyHWM=i,r._writeAlgorithm=o,r._closeAlgorithm=n,r._abortAlgorithm=a;var u=Ar(r);yr(e,u),p(d(t()),(function(){r._started=!0,Br(r)}),(function(t){r._started=!0,br(e,t)}))}function Wr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function jr(e){return e._strategyHWM-e._queueTotalSize}function Br(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===Pr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),fe(e);var t=e._closeAlgorithm();Wr(e),p(t,(function(){!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&xr(r)}(r)}),(function(e){!function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),br(e,r)}(r,e)}))}(e):function(e,r){var t=e._controlledWritableStream;(function(e){e._inFlightWriteRequest=e._writeRequests.shift()})(t),p(e._writeAlgorithm(r),(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(fe(e),!hr(t)&&"writable"===r){var o=Ar(e);yr(t,o)}Br(e)}),(function(r){"writable"===t._state&&Wr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,br(e,r)}(t,r)}))}(e,t)}}else _r(r)}function kr(e,r){"writable"===e._controlledWritableStream._state&&zr(e,r)}function Ar(e){return jr(e)<=0}function zr(e,r){var t=e._controlledWritableStream;Wr(e),pr(t,r)}function Dr(e){return new TypeError("WritableStream.prototype."+e+" can only be used on a WritableStream")}function Ir(e){return new TypeError("WritableStreamDefaultController.prototype."+e+" can only be used on a WritableStreamDefaultController")}function Fr(e){return new TypeError("WritableStreamDefaultWriter.prototype."+e+" can only be used on a WritableStreamDefaultWriter")}function Lr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Mr(e){e._closedPromise=c((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function Qr(e,r){Mr(e),Yr(e,r)}function Yr(e,r){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function xr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Nr(e){e._readyPromise=c((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function Hr(e,r){Nr(e),Ur(e,r)}function Vr(e){Nr(e),Gr(e)}function Ur(e,r){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Gr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(qr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(qr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var Xr="undefined"!=typeof DOMException?DOMException:void 0;var Jr,Kr=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Xr)?Xr:((Jr=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}).prototype=Object.create(Error.prototype),Object.defineProperty(Jr.prototype,"constructor",{value:Jr,writable:!0,configurable:!0}),Jr);function Zr(e,r,o,n,a,i){var l=V(e),u=lr(r);e._disturbed=!0;var s=!1,m=d(void 0);return c((function(v,g){var S,w,R,T;if(void 0!==i){if(S=function(){var t=new Kr("Aborted","AbortError"),o=[];n||o.push((function(){return"writable"===r._state?dr(r,t):d(void 0)})),a||o.push((function(){return"readable"===e._state?Tt(e,t):d(void 0)})),E((function(){return Promise.all(o.map((function(e){return e()})))}),!0,t)},i.aborted)return void S();i.addEventListener("abort",S)}if(O(e,l._closedPromise,(function(e){n?W(!0,e):E((function(){return dr(r,e)}),!0,e)})),O(r,u._closedPromise,(function(r){a?W(!0,r):E((function(){return Tt(e,r)}),!0,r)})),w=e,R=l._closedPromise,T=function(){o?W():E((function(){return function(e){var r=e._ownerWritableStream,t=r._state;return hr(r)||"closed"===t?d(void 0):"errored"===t?f(r._storedError):Sr(e)}(u)}))},"closed"===w._state?T():_(R,T),hr(r)||"closed"===r._state){var P=new TypeError("the destination writable stream closed before all data could be piped to it");a?W(!0,P):E((function(){return Tt(e,P)}),!0,P)}function q(){var e=m;return b(m,(function(){return e!==m?q():void 0}))}function O(e,r,t){"errored"===e._state?t(e._storedError):h(r,t)}function E(e,t,o){function n(){p(e(),(function(){return j(t,o)}),(function(e){return j(!0,e)}))}s||(s=!0,"writable"!==r._state||hr(r)?n():_(q(),n))}function W(e,t){s||(s=!0,"writable"!==r._state||hr(r)?j(e,t):_(q(),(function(){return j(e,t)})))}function j(e,r){Tr(u),C(l),void 0!==i&&i.removeEventListener("abort",S),e?g(r):v(void 0)}y(c((function(e,r){!function o(n){n?e():b(s?d(!0):b(u._readyPromise,(function(){return c((function(e,r){re(l,{_chunkSteps:function(r){m=b(Cr(u,r),void 0,t),e(!1)},_closeSteps:function(){return e(!0)},_errorSteps:r})}))})),o,r)}(!1)})))}))}var $r=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!et(this))throw ct("desiredSize");return lt(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!et(this))throw ct("close");if(!ut(this))throw new TypeError("The stream is not in a state that permits close");nt(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!et(this))throw ct("enqueue");if(!ut(this))throw new TypeError("The stream is not in a state that permits enqueue");return at(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!et(this))throw ct("error");it(this,e)},ReadableStreamDefaultController.prototype[k]=function(e){pe(this);var r=this._cancelAlgorithm(e);return ot(this),r},ReadableStreamDefaultController.prototype[A]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=fe(this);this._closeRequested&&0===this._queue.length?(ot(this),Ct(r)):rt(this),e._chunkSteps(t)}else U(r,e),rt(this)},ReadableStreamDefaultController}();function et(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof $r)}function rt(e){tt(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,p(e._pullAlgorithm(),(function(){e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,rt(e))}),(function(r){it(e,r)}))))}function tt(e){var r=e._controlledReadableStream;return!!ut(e)&&(!!e._started&&(!!(Rt(r)&&X(r)>0)||lt(e)>0))}function ot(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function nt(e){if(ut(e)){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(ot(e),Ct(r))}}function at(e,r){if(ut(e)){var t=e._controlledReadableStream;if(Rt(t)&&X(t)>0)G(t,r,!1);else{var o=void 0;try{o=e._strategySizeAlgorithm(r)}catch(r){throw it(e,r),r}try{be(e,r,o)}catch(r){throw it(e,r),r}}rt(e)}}function it(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(pe(e),ot(e),Pt(t,r))}function lt(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function ut(e){var r=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===r}function st(e,r,t,o,n,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,pe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=o,r._cancelAlgorithm=n,e._readableStreamController=r,p(d(t()),(function(){r._started=!0,rt(r)}),(function(e){it(r,e)}))}function ct(e){return new TypeError("ReadableStreamDefaultController.prototype."+e+" can only be used on a ReadableStreamDefaultController")}function dt(e,r){return me(e._readableStreamController)?function(e){var r,t,o,n,a,i=V(e),l=!1,u=!1,s=!1,f=!1,b=!1,p=c((function(e){a=e}));function _(e){h(e._closedPromise,(function(r){e===i&&(Ae(o._readableStreamController,r),Ae(n._readableStreamController,r),f&&b||a(void 0))}))}function m(){Ue(i)&&(C(i),_(i=V(e))),re(i,{_chunkSteps:function(r){v((function(){u=!1,s=!1;var t=r,i=r;if(!f&&!b)try{i=de(r)}catch(r){return Ae(o._readableStreamController,r),Ae(n._readableStreamController,r),void a(Tt(e,r))}f||ke(o._readableStreamController,t),b||ke(n._readableStreamController,i),l=!1,u?g():s&&S()}))},_closeSteps:function(){l=!1,f||Be(o._readableStreamController),b||Be(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Ie(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Ie(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:function(){l=!1}})}function y(r,t){ee(i)&&(C(i),_(i=Ye(e)));var c=t?n:o,d=t?o:n;Ge(i,r,{_chunkSteps:function(r){v((function(){u=!1,s=!1;var o=t?b:f;if(t?f:b)o||Fe(c._readableStreamController,r);else{var n=void 0;try{n=de(r)}catch(r){return Ae(c._readableStreamController,r),Ae(d._readableStreamController,r),void a(Tt(e,r))}o||Fe(c._readableStreamController,r),ke(d._readableStreamController,n)}l=!1,u?g():s&&S()}))},_closeSteps:function(e){l=!1;var r=t?b:f,o=t?f:b;r||Be(c._readableStreamController),o||Be(d._readableStreamController),void 0!==e&&(r||Fe(c._readableStreamController,e),!o&&d._readableStreamController._pendingPullIntos.length>0&&Ie(d._readableStreamController,0)),r&&o||a(void 0)},_errorSteps:function(){l=!1}})}function g(){if(l)return u=!0,d(void 0);l=!0;var e=ze(o._readableStreamController);return null===e?m():y(e._view,!1),d(void 0)}function S(){if(l)return s=!0,d(void 0);l=!0;var e=ze(n._readableStreamController);return null===e?m():y(e._view,!0),d(void 0)}function w(o){if(f=!0,r=o,b){var n=ue([r,t]),i=Tt(e,n);a(i)}return p}function R(o){if(b=!0,t=o,f){var n=ue([r,t]),i=Tt(e,n);a(i)}return p}function T(){}return o=gt(T,g,w),n=gt(T,S,R),_(i),[o,n]}(e):function(e,r){var t,o,n,a,i,l=V(e),u=!1,s=!1,f=!1,b=!1,p=c((function(e){i=e}));function _(){return u?(s=!0,d(void 0)):(u=!0,re(l,{_chunkSteps:function(e){v((function(){s=!1;var r=e,t=e;f||at(n._readableStreamController,r),b||at(a._readableStreamController,t),u=!1,s&&_()}))},_closeSteps:function(){u=!1,f||nt(n._readableStreamController),b||nt(a._readableStreamController),f&&b||i(void 0)},_errorSteps:function(){u=!1}}),d(void 0))}function m(r){if(f=!0,t=r,b){var n=ue([t,o]),a=Tt(e,n);i(a)}return p}function y(r){if(b=!0,o=r,f){var n=ue([t,o]),a=Tt(e,n);i(a)}return p}function g(){}return n=vt(g,_,m),a=vt(g,_,y),h(l._closedPromise,(function(e){it(n._readableStreamController,e),it(a._readableStreamController,e),f&&b||i(void 0)})),[n,a]}(e)}function ft(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function bt(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function pt(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function _t(e,r){if("bytes"!==(e=""+e))throw new TypeError(r+" '"+e+"' is not a valid enumeration value for ReadableStreamType");return e}function ht(e,r){if("byob"!==(e=""+e))throw new TypeError(r+" '"+e+"' is not a valid enumeration value for ReadableStreamReaderMode");return e}function mt(e,r){I(e,r);var t=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(r+" is not an AbortSignal.")}(a,r+" has member 'signal' that"),{preventAbort:Boolean(t),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties($r.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty($r.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var yt=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:L(e,"First parameter");var t=Ze(r,"Second parameter"),o=function(e,r){I(e,r);var t=e,o=null==t?void 0:t.autoAllocateChunkSize,n=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,l=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,r+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:ft(n,t,r+" has member 'cancel' that"),pull:void 0===a?void 0:bt(a,t,r+" has member 'pull' that"),start:void 0===i?void 0:pt(i,t,r+" has member 'start' that"),type:void 0===l?void 0:_t(l,r+" has member 'type' that")}}(e,"First parameter");if(St(this),"bytes"===o.type){if(void 0!==t.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,r,t){var o=Object.create(he.prototype),n=function(){},a=function(){return d(void 0)},i=function(){return d(void 0)};void 0!==r.start&&(n=function(){return r.start(o)}),void 0!==r.pull&&(a=function(){return r.pull(o)}),void 0!==r.cancel&&(i=function(e){return r.cancel(e)});var l=r.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Le(e,o,n,a,i,t,l)}(this,o,Je(t,0))}else{var n=Ke(t);!function(e,r,t,o){var n=Object.create($r.prototype),a=function(){},i=function(){return d(void 0)},l=function(){return d(void 0)};void 0!==r.start&&(a=function(){return r.start(n)}),void 0!==r.pull&&(i=function(){return r.pull(n)}),void 0!==r.cancel&&(l=function(e){return r.cancel(e)}),st(e,n,a,i,l,t,o)}(this,o,Je(t,1),n)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!wt(this))throw qt("locked");return Rt(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),wt(this)?Rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Tt(this,e):f(qt("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!wt(this))throw qt("getReader");return void 0===function(e,r){I(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:ht(t,r+" has member 'mode' that")}}(e,"First parameter").mode?V(this):Ye(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!wt(this))throw qt("pipeThrough");M(e,1,"pipeThrough");var t=function(e,r){I(e,r);var t=null==e?void 0:e.readable;Q(t,"readable","ReadableWritablePair"),H(t,r+" has member 'readable' that");var o=null==e?void 0:e.writable;return Q(o,"writable","ReadableWritablePair"),nr(o,r+" has member 'writable' that"),{readable:t,writable:o}}(e,"First parameter"),o=mt(r,"Second parameter");if(Rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(cr(t.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(Zr(this,t.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!wt(this))return f(qt("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!sr(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=mt(r,"Second parameter")}catch(e){return f(e)}return Rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):cr(e)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Zr(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!wt(this))throw qt("tee");return ue(dt(this))},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!wt(this))throw qt("values");var r,t,o,n,a,i=function(e,r){I(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,o=V(r),n=new oe(o,t),(a=Object.create(ne))._asyncIteratorImpl=n,a},ReadableStream}();function vt(e,r,t,o,n){void 0===o&&(o=1),void 0===n&&(n=function(){return 1});var a=Object.create(yt.prototype);return St(a),st(a,Object.create($r.prototype),e,r,t,o,n),a}function gt(e,r,t){var o=Object.create(yt.prototype);return St(o),Le(o,Object.create(he.prototype),e,r,t,0,void 0),o}function St(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function wt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof yt)}function Rt(e){return void 0!==e._reader}function Tt(e,r){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);Ct(e);var o=e._reader;return void 0!==o&&Ue(o)&&(o._readIntoRequests.forEach((function(e){e._closeSteps(void 0)})),o._readIntoRequests=new w),m(e._readableStreamController[k](r),t)}function Ct(e){e._state="closed";var r=e._reader;void 0!==r&&(W(r),ee(r)&&(r._readRequests.forEach((function(e){e._closeSteps()})),r._readRequests=new w))}function Pt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(E(t,r),ee(t)?(t._readRequests.forEach((function(e){e._errorSteps(r)})),t._readRequests=new w):(t._readIntoRequests.forEach((function(e){e._errorSteps(r)})),t._readIntoRequests=new w))}function qt(e){return new TypeError("ReadableStream.prototype."+e+" can only be used on a ReadableStream")}function Ot(e,r){I(e,r);var t=null==e?void 0:e.highWaterMark;return Q(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(t)}}Object.defineProperties(yt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(yt.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof r.asyncIterator&&Object.defineProperty(yt.prototype,r.asyncIterator,{value:yt.prototype.values,writable:!0,configurable:!0});var Et=function(e){return e.byteLength};try{Object.defineProperty(Et,"name",{value:"size",configurable:!0})}catch(K){}var Wt=function(){function ByteLengthQueuingStrategy(e){M(e,1,"ByteLengthQueuingStrategy"),e=Ot(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!Bt(this))throw jt("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!Bt(this))throw jt("size");return Et},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function jt(e){return new TypeError("ByteLengthQueuingStrategy.prototype."+e+" can only be used on a ByteLengthQueuingStrategy")}function Bt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof Wt)}Object.defineProperties(Wt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Wt.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var kt=function(){return 1};try{Object.defineProperty(kt,"name",{value:"size",configurable:!0})}catch(K){}var At=function(){function CountQueuingStrategy(e){M(e,1,"CountQueuingStrategy"),e=Ot(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!Dt(this))throw zt("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!Dt(this))throw zt("size");return kt},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function zt(e){return new TypeError("CountQueuingStrategy.prototype."+e+" can only be used on a CountQueuingStrategy")}function Dt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof At)}function It(e,r,t){return F(e,t),function(t){return S(e,r,[t])}}function Ft(e,r,t){return F(e,t),function(t){return g(e,r,[t])}}function Lt(e,r,t){return F(e,t),function(t,o){return S(e,r,[t,o])}}Object.defineProperties(At.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(At.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var Mt=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var o=Ze(r,"Second parameter"),n=Ze(t,"Third parameter"),a=function(e,r){I(e,r);var t=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===t?void 0:It(t,e,r+" has member 'flush' that"),readableType:o,start:void 0===n?void 0:Ft(n,e,r+" has member 'start' that"),transform:void 0===a?void 0:Lt(a,e,r+" has member 'transform' that"),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,l=Je(n,0),u=Ke(n),s=Je(o,1),b=Ke(o);!function(e,r,t,o,n,a){function i(){return r}function l(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return m(e._backpressureChangePromise,(function(){var o=e._writable;if("erroring"===o._state)throw o._storedError;return Xt(t,r)}))}return Xt(t,r)}(e,r)}function u(r){return function(e,r){return Yt(e,r),d(void 0)}(e,r)}function s(){return function(e){var r=e._readable,t=e._transformStreamController,o=t._flushAlgorithm();return Ut(t),m(o,(function(){if("errored"===r._state)throw r._storedError;nt(r._readableStreamController)}),(function(t){throw Yt(e,t),r._storedError}))}(e)}function c(){return function(e){return Nt(e,!1),e._backpressureChangePromise}(e)}function f(r){return xt(e,r),d(void 0)}e._writable=function(e,r,t,o,n,a){void 0===n&&(n=1),void 0===a&&(a=function(){return 1});var i=Object.create(ir.prototype);return ur(i),Er(i,Object.create(qr.prototype),e,r,t,o,n,a),i}(i,l,s,u,t,o),e._readable=vt(i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Nt(e,!0),e._transformStreamController=void 0}(this,c((function(e){i=e})),s,b,l,u),function(e,r){var t=Object.create(Ht.prototype),o=function(e){try{return Gt(t,e),d(void 0)}catch(e){return f(e)}},n=function(){return d(void 0)};void 0!==r.transform&&(o=function(e){return r.transform(e,t)});void 0!==r.flush&&(n=function(){return r.flush(t)});!function(e,r,t,o){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=o}(e,t,o,n)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!Qt(this))throw Kt("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!Qt(this))throw Kt("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function Qt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof Mt)}function Yt(e,r){it(e._readable._readableStreamController,r),xt(e,r)}function xt(e,r){Ut(e._transformStreamController),kr(e._writable._writableStreamController,r),e._backpressure&&Nt(e,!1)}function Nt(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(Mt.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Mt.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var Ht=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!Vt(this))throw Jt("desiredSize");return lt(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!Vt(this))throw Jt("enqueue");Gt(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Vt(this))throw Jt("error");var r;r=e,Yt(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!Vt(this))throw Jt("terminate");!function(e){var r=e._controlledTransformStream;nt(r._readable._readableStreamController);var t=new TypeError("TransformStream terminated");xt(r,t)}(this)},TransformStreamDefaultController}();function Vt(e){return!!n(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Ht)}function Ut(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Gt(e,r){var t=e._controlledTransformStream,o=t._readable._readableStreamController;if(!ut(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{at(o,r)}catch(e){throw xt(t,e),t._readable._storedError}(function(e){return!tt(e)})(o)!==t._backpressure&&Nt(t,!0)}function Xt(e,r){return m(e._transformAlgorithm(r),void 0,(function(r){throw Yt(e._controlledTransformStream,r),r}))}function Jt(e){return new TypeError("TransformStreamDefaultController.prototype."+e+" can only be used on a TransformStreamDefaultController")}function Kt(e){return new TypeError("TransformStream.prototype."+e+" can only be used on a TransformStream")}Object.defineProperties(Ht.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ht.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Zt={ReadableStream:yt,ReadableStreamDefaultController:$r,ReadableByteStreamController:he,ReadableStreamBYOBRequest:_e,ReadableStreamDefaultReader:$,ReadableStreamBYOBReader:Ve,WritableStream:ir,WritableStreamDefaultController:qr,WritableStreamDefaultWriter:vr,ByteLengthQueuingStrategy:Wt,CountQueuingStrategy:At,TransformStream:Mt,TransformStreamDefaultController:Ht};if(void 0!==o)for(var $t in Zt)Object.prototype.hasOwnProperty.call(Zt,$t)&&Object.defineProperty(o,$t,{value:Zt[$t],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=Wt,e.CountQueuingStrategy=At,e.ReadableByteStreamController=he,e.ReadableStream=yt,e.ReadableStreamBYOBReader=Ve,e.ReadableStreamBYOBRequest=_e,e.ReadableStreamDefaultController=$r,e.ReadableStreamDefaultReader=$,e.TransformStream=Mt,e.TransformStreamDefaultController=Ht,e.WritableStream=ir,e.WritableStreamDefaultController=qr,e.WritableStreamDefaultWriter=vr,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=polyfill.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.min.js.map new file mode 100644 index 0000000..347ac89 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.min.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","globals","self","window","global","typeIsObject","x","rethrowAssertionErrorRejection","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseResolve","resolve","bind","originalPromiseReject","reject","newPromise","executor","promiseResolvedWith","value","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","fn","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","this","_front","_elements","_next","_back","_cursor","_size","Object","SimpleQueue","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","length","push","oldFront","newFront","oldCursor","newCursor","elements","callback","i","node","front","cursor","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","name","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","shift","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","AsyncIteratorPrototype","IsReadableStreamLocked","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","hasOwnProperty","_disturbed","_readableStreamController","defineProperties","cancel","enumerable","read","releaseLock","closed","toStringTag","defineProperty","configurable","asyncIterator","preventCancel","_preventCancel","ReadableStreamAsyncIteratorImpl","nextSteps","_this","_nextSteps","_ongoingPromise","returnSteps","_returnSteps","_isFinished","result","ReadableStreamAsyncIteratorPrototype","next","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","ArrayBufferSlice","buffer","begin","end","ArrayBuffer","CloneAsUint8Array","O","byteOffset","byteLength","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","view","isView","ReadableByteStreamControllerRespondWithNewView","respond","respondWithNewView","ReadableByteStreamController","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","ReadableByteStreamControllerGetDesiredSize","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","ReadableByteStreamControllerEnqueue","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","controller","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","min","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","ready","queue","headOfQueue","peek","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInternal","firstDescriptor","ReadableByteStreamControllerRespondInClosedState","remainderSize","remainder","ReadableByteStreamControllerRespondInReadableState","transferredBuffer","firstPendingPullInto","ReadableStreamError","byobRequest","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","close","enqueue","error","desiredSize","byobReaderBrandCheckException","ReadableStreamBYOBReaderRead","constructor","DataView","BYTES_PER_ELEMENT","ctor","emptyView","ReadableByteStreamControllerPullInto","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","WritableStream","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","forEach","writeRequest","abortRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","getWriter","locked","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","abortReason","NativeDOMException","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","action","actions","shutdownWithAction","all","map","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed_1","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","cloneE","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","clonedChunk","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","mode","convertPipeOptions","options","isAbortSignal","assertAbortSignal","Boolean","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","ReadableStream","rawOptions","convertReaderOptions","rawTransform","transform","readable","convertReadableWritablePair","destination","impl","convertIteratorOptions","convertQueuingStrategyInit","getReader","pipeThrough","pipeTo","tee","values","byteLengthSizeFunction","_byteLengthQueuingStrategyHighWaterMark","ByteLengthQueuingStrategy","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","_countQueuingStrategyHighWaterMark","CountQueuingStrategy","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","startPromise_resolve","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","TransformStream","IsTransformStream","IsTransformStreamDefaultController","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","terminate","exports","prop"],"mappings":"0PAEA,IAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACA,SAAAE,GAAe,MAAA,UAAUA,gBCHbC,KAeT,IAAMC,EAVS,oBAATC,KACFA,KACoB,oBAAXC,OACTA,OACoB,oBAAXC,OACTA,YADF,WCROC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,EAGlD,IAAMC,EAUPP,ECbAQ,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAyBJ,QAAQK,QAAQC,KAAKP,GAC9CQ,EAAwBP,QAAQQ,OAAOF,KAAKP,YAElCU,EAAcC,GAI5B,OAAO,IAAIX,EAAgBW,YAGbC,EAAuBC,GACrC,OAAOR,EAAuBQ,YAGhBC,EAA+BC,GAC7C,OAAOP,EAAsBO,YAGfC,EACdC,EACAC,EACAC,GAGA,OAAOjB,EAAoBkB,KAAKH,EAASC,EAAaC,YAGxCE,EACdJ,EACAC,EACAC,GACAH,EACEA,EAAmBC,EAASC,EAAaC,QACzCG,EACAvB,YAIYwB,EAAmBN,EAAqBC,GACtDG,EAAYJ,EAASC,YAGPM,EAAcP,EAA2BE,GACvDE,EAAYJ,OAASK,EAAWH,YAGlBM,EACdR,EACAS,EACAC,GACA,OAAOX,EAAmBC,EAASS,EAAoBC,YAGzCC,EAA0BX,GACxCD,EAAmBC,OAASK,EAAWvB,GAGlC,IAAM8B,EAA2C,WACtD,IAAMC,EAAuBrC,GAAWA,EAAQoC,eAChD,GAAoC,mBAAzBC,EACT,OAAOA,EAGT,IAAMC,EAAkBnB,OAAoBU,GAC5C,OAAO,SAACU,GAAmB,OAAAhB,EAAmBe,EAAiBC,IAPT,YAUxCC,EAAmCC,EAAiCC,EAAMC,GACxF,GAAiB,mBAANF,EACT,MAAM,IAAIG,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AAM,IAAI5kB,UAAU,wDAMtB,IACEic,GAAuC2I,EAAoBrf,GAC3D,MAAOe,GAIP,MAFAqd,GAA4C5hB,EAAQuE,GAE9CvE,EAAOqhB,UAAU7gB,uBZjHzBqK,GAEA,OAAI0P,GAA8C1P,IYkH7BiY,CAA+CD,KAC/C7iB,EAAOmS,eAE1BuP,GAA+B1hB,GAAQ,GAQ3C,SAASihB,GAAuDpW,EACArH,GAE9D,OAAOnG,EADkBwN,EAAWyX,oBAAoB9e,QACVtG,GAAW,SAAAiR,GAEvD,MADAgT,GAAqBtW,EAAWwX,2BAA4BlU,GACtDA,KAiFV,SAASiI,GAAqCrV,GAC5C,OAAO,IAAI9C,UACT,8CAA8C8C,6DAKlD,SAASsQ,GAA0BtQ,GACjC,OAAO,IAAI9C,UACT,6BAA6B8C,4CApMjCnC,OAAO+F,iBAAiBqd,GAAiCjmB,UAAW,CAClE0S,QAAS,CAAE5J,YAAY,GACvB6J,MAAO,CAAE7J,YAAY,GACrBke,UAAW,CAAEle,YAAY,GACzB8J,YAAa,CAAE9J,YAAY,KAEK,iBAAvB5J,EAAOgK,aAChBrG,OAAOsG,eAAe8c,GAAiCjmB,UAAWd,EAAOgK,YAAa,CACpFxI,MAAO,mCACP0I,cAAc,IC7TlB,IAAM6d,GAAU,CACd/E,kBACApE,mCACA3Q,gCACAZ,6BACAnF,8BACAkL,4BAEA+C,kBACAN,mCACAa,+BAEAwN,6BACAK,wBAEAiD,mBACAT,qCAIF,QAAuB,IAAZ3mB,EACT,IAAK,IAAM4nB,MAAQD,GACbpkB,OAAO7C,UAAUyI,eAAexH,KAAKgmB,GAASC,KAChDrkB,OAAOsG,eAAe7J,EAAS4nB,GAAM,CACnCxmB,MAAOumB,GAAQC,IACfnL,UAAU,EACV3S,cAAc"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.mjs b/node_modules/web-streams-polyfill/dist/polyfill.mjs new file mode 100644 index 0000000..e033af5 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.mjs @@ -0,0 +1,4360 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(" + description + ")"; }; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseResolve = Promise.resolve.bind(originalPromise); +var originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var queueMicrotask = (function () { + var globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + var resolvedPromise = promiseResolvedWith(undefined); + return function (fn) { return PerformPromiseThen(resolvedPromise, fn); }; +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(context + " is not an object."); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(context + " is not a function."); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(context + " is not an object."); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter " + position + " is required in '" + context + "'."); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(field + " is required in '" + context + "'."); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(context + " is not a finite number"); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(context + " is outside the accepted range of " + lowerBound + " to " + upperBound + ", inclusive"); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(context + " is not a ReadableStream."); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype." + name + " can only be used on a ReadableStreamDefaultReader"); +} + +/// +var _a; +var AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator." + name + " can only be used on a ReadableSteamAsyncIterator"); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be closed"); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be enqueued to"); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + var entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var elementSize = pullIntoDescriptor.elementSize; + var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + var ctor = view.constructor; + // try { + var buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + var remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer; + var byteOffset = chunk.byteOffset; + var byteLength = chunk.byteLength; + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype." + name + " can only be used on a ReadableStreamBYOBRequest"); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype." + name + " can only be used on a ReadableByteStreamController"); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamBYOBReader.prototype.read = function (view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype." + name + " can only be used on a ReadableStreamBYOBReader"); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, context + " has member 'size' that") + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, context + " has member 'abort' that"), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, context + " has member 'close' that"), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, context + " has member 'start' that"), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, context + " has member 'write' that"), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(context + " is not a WritableStream."); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in " + state + " state) is not in the writable state and cannot be closed")); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype." + name + " can only be used on a WritableStream"); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype." + name + " can only be used on a WritableStreamDefaultController"); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype." + name + " can only be used on a WritableStreamDefaultWriter"); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +var NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +var DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = new DOMException$1('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype." + name + " can only be used on a ReadableStreamDefaultController"); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, context + " has member 'autoAllocateChunkSize' that"), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, context + " has member 'cancel' that"), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, context + " has member 'pull' that"), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, context + " has member 'start' that"), + type: type === undefined ? undefined : convertReadableStreamType(type, context + " has member 'type' that") + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "" + type; + if (type !== 'bytes') { + throw new TypeError(context + " '" + type + "' is not a valid enumeration value for ReadableStreamType"); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, context + " has member 'mode' that") + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "" + mode; + if (mode !== 'byob') { + throw new TypeError(context + " '" + mode + "' is not a valid enumeration value for ReadableStreamReaderMode"); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, context + " has member 'signal' that"); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(context + " is not an AbortSignal."); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, context + " has member 'readable' that"); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, context + " has member 'writable' that"); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype." + name + " can only be used on a ReadableStream"); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype." + name + " can only be used on a ByteLengthQueuingStrategy"); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype." + name + " can only be used on a CountQueuingStrategy"); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, context + " has member 'flush' that"), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, context + " has member 'start' that"), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, context + " has member 'transform' that"), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + var flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + var controller = stream._transformStreamController; + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, function () { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, function (r) { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype." + name + " can only be used on a TransformStreamDefaultController"); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype." + name + " can only be used on a TransformStream"); +} + +var exports = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (var prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.mjs.map new file mode 100644 index 0000000..0d18d05 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './utils';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n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AE,IAAI,CAAC,EAAE;YACvD,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;gBACnC,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;gBAC9C,QAAQ,EAAE,IAAI;gBACd,YAAY,EAAE,IAAI;aACnB,CAAC,CAAC;SACJ;KACF;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js new file mode 100644 index 0000000..95561e5 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js @@ -0,0 +1,4213 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=ponyfill.es2018.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map new file mode 100644 index 0000000..0b4238f --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,WAAW,IAAI,UAAU,WAAW,GAAoB;;ICL5D;aAEgB,IAAI;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,SAAS,UAAU;QACjB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,OAAO,IAAI,CAAC;SACb;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAEM,MAAM,OAAO,GAAG,UAAU,EAAE;;aCdnB,YAAY,CAAC,CAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI;;ICbV,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,MAAM,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,C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DAAyD,CAAC,CAAC;IACjH,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY;QAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs new file mode 100644 index 0000000..f4ddff0 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs @@ -0,0 +1,4191 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseResolve = Promise.resolve.bind(originalPromise); +const originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } +} +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es2018.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map new file mode 100644 index 0000000..5057974 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;AAAA;AAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,Q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AAC,YAAY,CAAC;KAC7B,CAAC,CAAC;AACL,CAAC;AAED;AAEA,SAAS,yCAAyC,CAAC,MAAuB;;IAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;IAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;AAC3C,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY;IACxD,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,yDAAyD,CAAC,CAAC;AACjH,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY;IAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.js b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js new file mode 100644 index 0000000..338e6fe --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js @@ -0,0 +1,4224 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + let AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=ponyfill.es6.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map new file mode 100644 index 0000000..f2b0fdc --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,WAAW,IAAI,UAA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MAAW;;;QAGpF,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACrC,OAAO,mBAAmB,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;IAED,SAAS,wCAAwC,CAAO,MAA6B;;QAEnF,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC;QAElC,MAAM,UAAU,GAAG,MAAM,CAAC,0BAA0B,CAAC;QACrD,MAAM,YAAY,GAAG,UAAU,CAAC,eAAe,EAAE,CAAC;QAClD,+CAA+C,CAAC,UAAU,CAAC,CAAC;;QAG5D,OAAO,oBAAoB,CAAC,YAAY,EAAE;YACxC,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,EAAE;gBACjC,MAAM,QAAQ,CAAC,YAAY,CAAC;aAC7B;YACD,oCAAoC,CAAC,QAAQ,CAAC,yBAA+D,CAAC,CAAC;SAChH,EAAE,CAAC;YACF,oBAAoB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAChC,MAAM,QAAQ,CAAC,YAAY,CAAC;SAC7B,CAAC,CAAC;IACL,CAAC;IAED;IAEA,SAAS,yCAAyC,CAAC,MAAuB;;QAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;QAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;IAC3C,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY;QACxD,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,yDAAyD,CAAC,CAAC;IACjH,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY;QAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs new file mode 100644 index 0000000..84a6a3a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs @@ -0,0 +1,4202 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseResolve = Promise.resolve.bind(originalPromise); +const originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(undefined); + return (fn) => PerformPromiseThen(resolvedPromise, fn); +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +let AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + // try { + const buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, r => { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let writeAlgorithm = () => promiseResolvedWith(undefined); + let closeAlgorithm = () => promiseResolvedWith(undefined); + let abortAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = new DOMException$1('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, e => { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, r => { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => undefined; + let pullAlgorithm = () => promiseResolvedWith(undefined); + let cancelAlgorithm = () => promiseResolvedWith(undefined); + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } +} +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(undefined); + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, () => { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, r => { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es6.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map new file mode 100644 index 0000000..fd8b762 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;AAAA;AAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,MAAM;IACN,WAAW,IAAI,UAAU,WAAW,GAAoB;;ACL5D;SAEgB,IAAI;IAClB,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,UAAU;IACjB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAC/B,OAAO,IAAI,CAAC;KACb;SAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACxC,OAAO,MAAM,CAAC;KACf;SAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACxC,OAAO,MAAM,CAAC;KACf;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,MAAM,OAAO,GAAG,UAAU,EAAE;;SCdnB,YAAY,CAAC,CAAM;IACjC,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI;;ACbV,MAAM,eAAe,GAAG,OAAO,CAAC;AAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;AACnD,MAAM,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACrE,MAAM,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;SAEnD,UAAU,CAAI,QAGrB;IACP,OAAO,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;SAEe,mBAAmB,CAAI,KAAyB;IAC9D,OAAO,sBAAsB,CAAC,KAAK,CAAC,CAAC;AACvC,CAAC;SAEe,mBAAmB,CAAY,MAAW;IACxD,OAAO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AAU,CAAC,eAAe,EAAE,CAAC;IAClD,+CAA+C,CAAC,UAAU,CAAC,CAAC;;IAG5D,OAAO,oBAAoB,CAAC,YAAY,EAAE;QACxC,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,EAAE;YACjC,MAAM,QAAQ,CAAC,YAAY,CAAC;SAC7B;QACD,oCAAoC,CAAC,QAAQ,CAAC,yBAA+D,CAAC,CAAC;KAChH,EAAE,CAAC;QACF,oBAAoB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAChC,MAAM,QAAQ,CAAC,YAAY,CAAC;KAC7B,CAAC,CAAC;AACL,CAAC;AAED;AAEA,SAAS,yCAAyC,CAAC,MAAuB;;IAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;IAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;AAC3C,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY;IACxD,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,yDAAyD,CAAC,CAAC;AACjH,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY;IAC7C,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,wCAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.js b/node_modules/web-streams-polyfill/dist/ponyfill.js new file mode 100644 index 0000000..96cb3ab --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.js @@ -0,0 +1,4354 @@ +/** + * web-streams-polyfill v3.2.1 + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +}(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(" + description + ")"; }; + + /// + function noop() { + return undefined; + } + function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseResolve = Promise.resolve.bind(originalPromise); + var originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var queueMicrotask = (function () { + var globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + var resolvedPromise = promiseResolvedWith(undefined); + return function (fn) { return PerformPromiseThen(resolvedPromise, fn); }; + })(); + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(context + " is not an object."); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(context + " is not a function."); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(context + " is not an object."); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter " + position + " is required in '" + context + "'."); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(field + " is required in '" + context + "'."); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(context + " is not a finite number"); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(context + " is outside the accepted range of " + lowerBound + " to " + upperBound + ", inclusive"); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(context + " is not a ReadableStream."); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype." + name + " can only be used on a ReadableStreamDefaultReader"); + } + + /// + var _a; + var AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator." + name + " can only be used on a ReadableSteamAsyncIterator"); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + // Not implemented correctly + function TransferArrayBuffer(O) { + return O; + } + // Not implemented correctly + // eslint-disable-next-line @typescript-eslint/no-unused-vars + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be closed"); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be enqueued to"); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + var entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableByteStreamControllerError(controller, e); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var elementSize = pullIntoDescriptor.elementSize; + var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + var ctor = view.constructor; + // try { + var buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + var remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer; + var byteOffset = chunk.byteOffset; + var byteLength = chunk.byteLength; + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableByteStreamControllerError(controller, r); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype." + name + " can only be used on a ReadableStreamBYOBRequest"); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype." + name + " can only be used on a ReadableByteStreamController"); + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamBYOBReader.prototype.read = function (view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype." + name + " can only be used on a ReadableStreamBYOBReader"); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, context + " has member 'size' that") + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, context + " has member 'abort' that"), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, context + " has member 'close' that"), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, context + " has member 'start' that"), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, context + " has member 'write' that"), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(context + " is not a WritableStream."); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in " + state + " state) is not in the writable state and cannot be closed")); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype." + name + " can only be used on a WritableStream"); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype." + name + " can only be used on a WritableStreamDefaultController"); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype." + name + " can only be used on a WritableStreamDefaultWriter"); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + var NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line no-redeclare + var DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = new DOMException$1('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype." + name + " can only be used on a ReadableStreamDefaultController"); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, context + " has member 'autoAllocateChunkSize' that"), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, context + " has member 'cancel' that"), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, context + " has member 'pull' that"), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, context + " has member 'start' that"), + type: type === undefined ? undefined : convertReadableStreamType(type, context + " has member 'type' that") + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "" + type; + if (type !== 'bytes') { + throw new TypeError(context + " '" + type + "' is not a valid enumeration value for ReadableStreamType"); + } + return type; + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, context + " has member 'mode' that") + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "" + mode; + if (mode !== 'byob') { + throw new TypeError(context + " '" + mode + "' is not a valid enumeration value for ReadableStreamReaderMode"); + } + return mode; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, context + " has member 'signal' that"); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(context + " is not an AbortSignal."); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, context + " has member 'readable' that"); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, context + " has member 'writable' that"); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype." + name + " can only be used on a ReadableStream"); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype." + name + " can only be used on a ByteLengthQueuingStrategy"); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype." + name + " can only be used on a CountQueuingStrategy"); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, context + " has member 'flush' that"), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, context + " has member 'start' that"), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, context + " has member 'transform' that"), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + var flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + var controller = stream._transformStreamController; + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, function () { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, function (r) { + TransformStreamError(stream, r); + throw readable._storedError; + }); + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype." + name + " can only be used on a TransformStreamDefaultController"); + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype." + name + " can only be used on a TransformStream"); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=ponyfill.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.js.map new file mode 100644 index 0000000..87baccc --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;QACjE,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,YAAU,WAAW,MAAoB,GAAA;;ICL5D;aAEgB,IAAI;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,SAAS,UAAU;QACjB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,OAAO,IAAI,CAAC;SACb;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACxC,OAAO,MAAM,CAAC;SACf;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAEM,IAAM,OAAO,GAAG,UAAU,EAAE;;aCdnB,YAAY,CAAC,CAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,IAAM,8BAA8B,GAUrC,IAAI;;ICbV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C,CAAC,QAAQ,CAAC,yBAA+D,CAAC,CAAC;SAChH,EAAE,UAAA,CAAC;YACF,oBAAoB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAChC,MAAM,QAAQ,CAAC,YAAY,CAAC;SAC7B,CAAC,CAAC;IACL,CAAC;IAED;IAEA,SAAS,yCAAyC,CAAC,MAAuB;;QAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;QAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;IAC3C,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY;QACxD,OAAO,IAAI,SAAS,CAClB,gDAA8C,IAAI,4DAAyD,CAAC,CAAC;IACjH,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY;QAC7C,OAAO,IAAI,SAAS,CAClB,+BAA6B,IAAI,2CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.mjs new file mode 100644 index 0000000..43820d6 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.mjs @@ -0,0 +1,4332 @@ +/** + * web-streams-polyfill v3.2.1 + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(" + description + ")"; }; + +/// +function noop() { + return undefined; +} +function getGlobals() { + if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseResolve = Promise.resolve.bind(originalPromise); +var originalPromiseReject = Promise.reject.bind(originalPromise); +function newPromise(executor) { + return new originalPromise(executor); +} +function promiseResolvedWith(value) { + return originalPromiseResolve(value); +} +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var queueMicrotask = (function () { + var globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === 'function') { + return globalQueueMicrotask; + } + var resolvedPromise = promiseResolvedWith(undefined); + return function (fn) { return PerformPromiseThen(resolvedPromise, fn); }; +})(); +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + reader._ownerReadableStream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(context + " is not an object."); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(context + " is not a function."); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(context + " is not an object."); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter " + position + " is required in '" + context + "'."); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(field + " is required in '" + context + "'."); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(context + " is not a finite number"); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(context + " is outside the accepted range of " + lowerBound + " to " + upperBound + ", inclusive"); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(context + " is not a ReadableStream."); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype." + name + " can only be used on a ReadableStreamDefaultReader"); +} + +/// +var _a; +var AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('iterate')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (reader._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('finish iterating')); + } + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator." + name + " can only be used on a ReadableSteamAsyncIterator"); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +// Not implemented correctly +function TransferArrayBuffer(O) { + return O; +} +// Not implemented correctly +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function IsDetachedBuffer(O) { + return false; +} +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be closed"); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in " + state + " state) is not in the readable state and cannot be enqueued to"); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + var entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableByteStreamControllerError(controller, e); + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var elementSize = pullIntoDescriptor.elementSize; + var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + var ctor = view.constructor; + // try { + var buffer = TransferArrayBuffer(view.buffer); + // } catch (e) { + // readIntoRequest._errorSteps(e); + // return; + // } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + var remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer; + var byteOffset = chunk.byteOffset; + var byteLength = chunk.byteLength; + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableByteStreamControllerError(controller, r); + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype." + name + " can only be used on a ReadableStreamBYOBRequest"); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype." + name + " can only be used on a ReadableByteStreamController"); +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamBYOBReader.prototype.read = function (view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) ; + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + } + ReadableStreamReaderGenericRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype." + name + " can only be used on a ReadableStreamBYOBReader"); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, context + " has member 'size' that") + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, context + " has member 'abort' that"), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, context + " has member 'close' that"), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, context + " has member 'start' that"), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, context + " has member 'write' that"), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(context + " is not a WritableStream."); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in " + state + " state) is not in the writable state and cannot be closed")); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + var abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype." + name + " can only be used on a WritableStream"); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype." + name + " can only be used on a WritableStreamDefaultController"); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype." + name + " can only be used on a WritableStreamDefaultWriter"); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +var NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +function createDOMExceptionPolyfill() { + // eslint-disable-next-line no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line no-redeclare +var DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = new DOMException$1('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm = function () { return undefined; }; + var pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + var cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype." + name + " can only be used on a ReadableStreamDefaultController"); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, context + " has member 'autoAllocateChunkSize' that"), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, context + " has member 'cancel' that"), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, context + " has member 'pull' that"), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, context + " has member 'start' that"), + type: type === undefined ? undefined : convertReadableStreamType(type, context + " has member 'type' that") + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "" + type; + if (type !== 'bytes') { + throw new TypeError(context + " '" + type + "' is not a valid enumeration value for ReadableStreamType"); + } + return type; +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, context + " has member 'mode' that") + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "" + mode; + if (mode !== 'byob') { + throw new TypeError(context + " '" + mode + "' is not a valid enumeration value for ReadableStreamReaderMode"); + } + return mode; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, context + " has member 'signal' that"); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(context + " is not an AbortSignal."); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, context + " has member 'readable' that"); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, context + " has member 'writable' that"); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + reader._readIntoRequests = new SimpleQueue(); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + reader._readRequests = new SimpleQueue(); + } + else { + reader._readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + reader._readIntoRequests = new SimpleQueue(); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype." + name + " can only be used on a ReadableStream"); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +try { + Object.defineProperty(byteLengthSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype." + name + " can only be used on a ByteLengthQueuingStrategy"); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +try { + Object.defineProperty(countSizeFunction, 'name', { + value: 'size', + configurable: true + }); +} +catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype." + name + " can only be used on a CountQueuingStrategy"); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, context + " has member 'flush' that"), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, context + " has member 'start' that"), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, context + " has member 'transform' that"), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(undefined); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + var flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already + // errored. + TransformStreamError(stream, reason); + return promiseResolvedWith(undefined); +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + var controller = stream._transformStreamController; + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + // Return a promise that is fulfilled with undefined on success. + return transformPromiseWith(flushPromise, function () { + if (readable._state === 'errored') { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, function (r) { + TransformStreamError(stream, r); + throw readable._storedError; + }); +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype." + name + " can only be used on a TransformStreamDefaultController"); +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype." + name + " can only be used on a TransformStream"); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map new file mode 100644 index 0000000..2d74a3a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/readable-stream/generic-reader.ts","../src/lib/abstract-ops/internal-methods.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/stub/native.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/reader-options.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/// \n\nexport function noop(): undefined {\n return undefined;\n}\n\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n","import { globals } from '../../utils';\nimport { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return originalPromiseResolve(value);\n}\n\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => void | PromiseLike,\n onRejected?: (reason: any) => void | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => void | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => void | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nexport const queueMicrotask: (fn: () => void) => void = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn: () => void) => PerformPromiseThen(resolvedPromise, fn);\n})();\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._ownerReadableStream._reader === reader);\n\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadableStreamDefaultReadResult,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ndeclare class ReadableStreamAsyncIteratorInstance implements ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","export function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\n// Not implemented correctly\nexport function TransferArrayBuffer(O: T): T {\n return O;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function CanTransferArrayBuffer(O: ArrayBufferLike): boolean {\n return true;\n}\n\n// Not implemented correctly\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function IsDetachedBuffer(O: ArrayBufferLike): boolean {\n return false;\n}\n\nexport function ArrayBufferSlice(buffer: ArrayBufferLike, begin: number, end: number): ArrayBufferLike {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: ArrayBufferView): Uint8Array {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: ArrayBufferView | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: ArrayBufferView | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ArrayBufferViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n readonly BYTES_PER_ELEMENT: number;\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBufferLike;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'default';\n}\n\ninterface BYOBPullIntoDescriptor {\n buffer: ArrayBufferLike;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: ArrayBufferView | undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n const entry = this._queue.shift()!;\n this._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(this);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n\n readRequest._chunkSteps(view);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBufferLike,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nexport function ReadableByteStreamControllerPullInto(\n controller: ReadableByteStreamController,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = (view.constructor as ArrayBufferViewConstructor).BYTES_PER_ELEMENT;\n }\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n\n // try {\n const buffer = TransferArrayBuffer(view.buffer);\n // } catch (e) {\n // readIntoRequest._errorSteps(e);\n // return;\n // }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled === 0);\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n }\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: ArrayBufferView) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableByteStream, ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest(stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableByteStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view: T): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n\n ReadableStreamReaderGenericRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead(\n reader: ReadableStreamBYOBReader,\n view: T,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n readIntoRequest\n );\n }\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { AbortController, AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight,\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort();\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let writeAlgorithm: (chunk: W) => Promise = () => promiseResolvedWith(undefined);\n let closeAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let abortAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \nexport const NativeDOMException: typeof DOMException | undefined =\n typeof DOMException !== 'undefined' ? DOMException : undefined;\n","/// \nimport { NativeDOMException } from './native';\n\ndeclare class DOMExceptionClass extends Error {\n constructor(message?: string, name?: string);\n\n name: string;\n message: string;\n}\n\ntype DOMException = DOMExceptionClass;\ntype DOMExceptionConstructor = typeof DOMExceptionClass;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction createDOMExceptionPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line no-redeclare\nconst DOMException: DOMExceptionConstructor =\n isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => void) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => void) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest() {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n }\n });\n}\n","import { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport { ValidatedUnderlyingSource } from './underlying-source';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike = () => undefined;\n let pullAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n let cancelAlgorithm: (reason: any) => Promise = () => promiseResolvedWith(undefined);\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n IsReadableStream,\n ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultController,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableStream;\n let branch2: ReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(\n branch1._readableStreamController as ReadableStreamDefaultController,\n chunk1\n );\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(\n branch2._readableStreamController as ReadableStreamDefaultController,\n chunk2\n );\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController as ReadableStreamDefaultController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController as ReadableStreamDefaultController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController as ReadableStreamDefaultController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController as ReadableStreamDefaultController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: ArrayBufferView, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport { ReadableStreamGetReaderOptions } from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n","import { assertDictionary } from './basic';\nimport {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\n\nexport type ReadableByteStream = ReadableStream & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n}\n\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1): ReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: ReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n\n reader._readRequests = new SimpleQueue();\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\ntry {\n Object.defineProperty(byteLengthSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\ntry {\n Object.defineProperty(countSizeFunction, 'name', {\n value: 'size',\n configurable: true\n });\n} catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n}\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import assert from '../stub/assert';\nimport { newPromise, promiseRejectedWith, promiseResolvedWith, transformPromiseWith } from './helpers/webidl';\nimport { CreateReadableStream, ReadableStream, ReadableStreamDefaultController } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport {\n Transformer,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: ReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport {\n Transformer,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(\n stream._readable._readableStreamController as ReadableStreamDefaultController,\n e\n );\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController as ReadableStreamDefaultController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm = (chunk: I): Promise => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n\n let flushAlgorithm: () => Promise = () => promiseResolvedWith(undefined);\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController as ReadableStreamDefaultController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController as ReadableStreamDefaultController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","streamBrandCheckException","defaultControllerBrandCheckException","DOMException"],"mappings":";;;AAAA;AAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,Q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MAAM,QAAQ,CAAC,YAAY,CAAC;SAC7B;QACD,oCAAoC,CAAC,QAAQ,CAAC,yBAA+D,CAAC,CAAC;KAChH,EAAE,UAAA,CAAC;QACF,oBAAoB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAChC,MAAM,QAAQ,CAAC,YAAY,CAAC;KAC7B,CAAC,CAAC;AACL,CAAC;AAED;AAEA,SAAS,yCAAyC,CAAC,MAAuB;;IAMxE,8BAA8B,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;IAG9C,OAAO,MAAM,CAAC,0BAA0B,CAAC;AAC3C,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY;IACxD,OAAO,IAAI,SAAS,CAClB,gDAA8C,IAAI,4DAAyD,CAAC,CAAC;AACjH,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY;IAC7C,OAAO,IAAI,SAAS,CAClB,+BAA6B,IAAI,2CAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts new file mode 100644 index 0000000..e44c663 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts @@ -0,0 +1,771 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + readonly size: (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + readonly size: (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +declare type QueuingStrategySizeCallback = (chunk: T) => number; + +declare type ReadableByteStream = ReadableStream & { + _readableStreamController: ReadableByteStreamController; +}; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + readonly byobRequest: ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + readonly locked: boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableByteStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + readonly view: ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + readonly readable: ReadableStream; + /** + * The writable side of the transform stream. + */ + readonly writable: WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + readonly desiredSize: number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + readonly locked: boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + readonly abortReason: any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + readonly signal: AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + readonly desiredSize: number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + readonly ready: Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts new file mode 100644 index 0000000..c398f7e --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts @@ -0,0 +1,771 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size(): (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size(): (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +declare type QueuingStrategySizeCallback = (chunk: T) => number; + +declare type ReadableByteStream = ReadableStream & { + _readableStreamController: ReadableByteStreamController; +}; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked(): boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, + * i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. + * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream + * into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under + * various error conditions can be customized with a number of passed options. It returns a promise that fulfills + * when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableByteStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view(): ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + get readable(): ReadableStream; + /** + * The writable side of the transform stream. + */ + get writable(): WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize(): number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked(): boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason(): any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal(): AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize(): number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready(): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json b/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json new file mode 100644 index 0000000..e86846c --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.13.4" + } + ] +} diff --git a/node_modules/web-streams-polyfill/es2018/package.json b/node_modules/web-streams-polyfill/es2018/package.json new file mode 100644 index 0000000..878ab2d --- /dev/null +++ b/node_modules/web-streams-polyfill/es2018/package.json @@ -0,0 +1,7 @@ +{ + "name": "web-streams-polyfill-es2018", + "main": "../dist/polyfill.es2018", + "browser": "../dist/polyfill.es2018.min.js", + "module": "../dist/polyfill.es2018.mjs", + "types": "../dist/types/polyfill.d.ts" +} diff --git a/node_modules/web-streams-polyfill/es6/package.json b/node_modules/web-streams-polyfill/es6/package.json new file mode 100644 index 0000000..ebdd02d --- /dev/null +++ b/node_modules/web-streams-polyfill/es6/package.json @@ -0,0 +1,7 @@ +{ + "name": "web-streams-polyfill-es6", + "main": "../dist/polyfill.es6", + "browser": "../dist/polyfill.es6.min.js", + "module": "../dist/polyfill.es6.mjs", + "types": "../dist/types/polyfill.d.ts" +} diff --git a/node_modules/web-streams-polyfill/package.json b/node_modules/web-streams-polyfill/package.json new file mode 100644 index 0000000..af3208a --- /dev/null +++ b/node_modules/web-streams-polyfill/package.json @@ -0,0 +1,76 @@ +{ + "name": "web-streams-polyfill", + "version": "3.2.1", + "description": "Web Streams, based on the WHATWG spec reference implementation", + "main": "dist/polyfill", + "browser": "dist/polyfill.min.js", + "module": "dist/polyfill.mjs", + "types": "dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "dist/types/*": [ + "dist/types/ts3.6/*" + ] + } + }, + "scripts": { + "test": "npm run test:types && npm run test:unit && npm run test:wpt", + "test:wpt": "node --expose_gc ./test/run-web-platform-tests.js", + "pretest:wpt": "git submodule update --init --recursive", + "test:types": "tsc -p ./test/types/tsconfig.json", + "test:unit": "jasmine --config=test/unit/jasmine.json", + "lint": "eslint \"src/**/*.ts\"", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "rollup -c", + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run && node ./build/downlevel-dts.js", + "accept:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run --local && node ./build/downlevel-dts.js", + "prepare": "npm run build" + }, + "files": [ + "dist", + "es6", + "es2018", + "ponyfill" + ], + "engines": { + "node": ">= 8" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git" + }, + "keywords": [ + "streams", + "whatwg", + "polyfill" + ], + "author": "Mattias Buelens ", + "contributors": [ + "Diwank Singh " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues" + }, + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme", + "devDependencies": { + "@microsoft/api-extractor": "^7.13.4", + "@rollup/plugin-inject": "^4.0.2", + "@rollup/plugin-replace": "^2.4.2", + "@rollup/plugin-strip": "^2.0.0", + "@rollup/plugin-typescript": "^8.2.1", + "@types/node": "^14.14.37", + "@typescript-eslint/eslint-plugin": "^4.21.0", + "@typescript-eslint/parser": "^4.21.0", + "@ungap/promise-all-settled": "^1.1.2", + "eslint": "^7.23.0", + "jasmine": "^3.7.0", + "micromatch": "^4.0.2", + "rollup": "^2.44.0", + "rollup-plugin-terser": "^7.0.2", + "ts-morph": "^10.0.2", + "tslib": "^2.2.0", + "typescript": "^4.2.4", + "wpt-runner": "^3.2.1" + } +} diff --git a/node_modules/web-streams-polyfill/ponyfill/es2018/package.json b/node_modules/web-streams-polyfill/ponyfill/es2018/package.json new file mode 100644 index 0000000..3d73b0b --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/es2018/package.json @@ -0,0 +1,6 @@ +{ + "name": "web-streams-ponyfill-es2018", + "main": "../../dist/ponyfill.es2018", + "module": "../../dist/ponyfill.es2018.mjs", + "types": "../../dist/types/polyfill.d.ts" +} diff --git a/node_modules/web-streams-polyfill/ponyfill/es6/package.json b/node_modules/web-streams-polyfill/ponyfill/es6/package.json new file mode 100644 index 0000000..d74a94a --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/es6/package.json @@ -0,0 +1,6 @@ +{ + "name": "web-streams-ponyfill-es6", + "main": "../../dist/ponyfill.es6", + "module": "../../dist/ponyfill.es6.mjs", + "types": "../../dist/types/polyfill.d.ts" +} diff --git a/node_modules/web-streams-polyfill/ponyfill/package.json b/node_modules/web-streams-polyfill/ponyfill/package.json new file mode 100644 index 0000000..384e4dd --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/package.json @@ -0,0 +1,6 @@ +{ + "name": "web-streams-ponyfill", + "main": "../dist/ponyfill", + "module": "../dist/ponyfill.mjs", + "types": "../dist/types/polyfill.d.ts" +} diff --git a/node_modules/ws/LICENSE b/node_modules/ws/LICENSE new file mode 100644 index 0000000..65ff176 --- /dev/null +++ b/node_modules/ws/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Einar Otto Stangvik + +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/node_modules/ws/README.md b/node_modules/ws/README.md new file mode 100644 index 0000000..b78b1f6 --- /dev/null +++ b/node_modules/ws/README.md @@ -0,0 +1,493 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/workflow/status/websockets/ws/CI/master?label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [echo.websocket.org demo](#echowebsocketorg-demo) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons which improve certain operations. +Prebuilt binaries are available for the most popular platforms so you don't +necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a + message contains valid UTF-8. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function incoming(message) { + console.log('received: %s', message); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { parse } from 'url'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + // ... +}); + +wss2.on('connection', function connection(ws) { + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = parse(request.url); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import WebSocket from 'ws'; +import { createServer } from 'http'; + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('message', function message(msg) { + console.log(`Received message ${msg} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, (err, client) => { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### echo.websocket.org demo + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://echo.websocket.org/', { + origin: 'https://websocket.org' +}); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function incoming(data) { + console.log(`Roundtrip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://echo.websocket.org/', { + origin: 'https://websocket.org' +}); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a way +that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://echo.websocket.org/'); + +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[ws-server-options]: + https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback diff --git a/node_modules/ws/browser.js b/node_modules/ws/browser.js new file mode 100644 index 0000000..ca4f628 --- /dev/null +++ b/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/node_modules/ws/index.js b/node_modules/ws/index.js new file mode 100644 index 0000000..41edb3b --- /dev/null +++ b/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/node_modules/ws/lib/buffer-util.js b/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000..1ba1d1b --- /dev/null +++ b/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,126 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) return target.slice(0, offset); + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +try { + const bufferUtil = require('bufferutil'); + + module.exports = { + concat, + mask(source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }, + toArrayBuffer, + toBuffer, + unmask(buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + } + }; +} catch (e) /* istanbul ignore next */ { + module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask + }; +} diff --git a/node_modules/ws/lib/constants.js b/node_modules/ws/lib/constants.js new file mode 100644 index 0000000..d691b30 --- /dev/null +++ b/node_modules/ws/lib/constants.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/node_modules/ws/lib/event-target.js b/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000..d5abd83 --- /dev/null +++ b/node_modules/ws/lib/event-target.js @@ -0,0 +1,266 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {Function} listener The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, listener, options = {}) { + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + listener.call(this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + listener.call(this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + listener.call(this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + listener.call(this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = listener; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; diff --git a/node_modules/ws/lib/extension.js b/node_modules/ws/lib/extension.js new file mode 100644 index 0000000..3d7895c --- /dev/null +++ b/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/node_modules/ws/lib/limiter.js b/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000..3fd3578 --- /dev/null +++ b/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/node_modules/ws/lib/permessage-deflate.js b/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000..5040697 --- /dev/null +++ b/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,511 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) data = data.slice(0, data.length - 4); + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/node_modules/ws/lib/receiver.js b/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000..e11e266 --- /dev/null +++ b/node_modules/ws/lib/receiver.js @@ -0,0 +1,612 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = buf.slice(n); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: + // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (this._payloadLength > 0x7d) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + if (this._masked) unmask(data, this._mask); + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else if (data.length === 1) { + return error( + RangeError, + 'invalid payload length 1', + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = data.slice(2); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + } else { + this.emit('pong', data); + } + + this._state = GET_INFO; + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; +} diff --git a/node_modules/ws/lib/sender.js b/node_modules/ws/lib/sender.js new file mode 100644 index 0000000..c1e357c --- /dev/null +++ b/node_modules/ws/lib/sender.js @@ -0,0 +1,422 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ + +'use strict'; + +const net = require('net'); +const tls = require('tls'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER } = require('./constants'); +const { isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const mask = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {(net.Socket|tls.Socket)} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + */ + constructor(socket, extensions) { + this._extensions = extensions || {}; + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {Buffer} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {Buffer[]} The framed data as a list of `Buffer` instances + * @public + */ + static frame(data, options) { + const merge = options.mask && options.readOnly; + let offset = options.mask ? 6 : 2; + let payloadLength = data.length; + + if (data.length >= 65536) { + offset += 8; + payloadLength = 127; + } else if (data.length > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(data.length, 2); + } else if (payloadLength === 127) { + target.writeUInt32BE(0, 2); + target.writeUInt32BE(data.length, 6); + } + + if (!options.mask) return [target, data]; + + randomFillSync(mask, 0, 4); + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (merge) { + applyMask(data, mask, target, offset, data.length); + return [target]; + } + + applyMask(data, mask, data, 0, data.length); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + if (this._deflating) { + this.enqueue([this.doClose, buf, mask, cb]); + } else { + this.doClose(buf, mask, cb); + } + } + + /** + * Frames and sends a close message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @private + */ + doClose(data, mask, cb) { + this.sendFrame( + Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x08, + mask, + readOnly: false + }), + cb + ); + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + const buf = toBuffer(data); + + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + if (this._deflating) { + this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]); + } else { + this.doPing(buf, mask, toBuffer.readOnly, cb); + } + } + + /** + * Frames and sends a ping message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified + * @param {Function} [cb] Callback + * @private + */ + doPing(data, mask, readOnly, cb) { + this.sendFrame( + Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x09, + mask, + readOnly + }), + cb + ); + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + const buf = toBuffer(data); + + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + if (this._deflating) { + this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]); + } else { + this.doPong(buf, mask, toBuffer.readOnly, cb); + } + } + + /** + * Frames and sends a pong message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified + * @param {Function} [cb] Callback + * @private + */ + doPong(data, mask, readOnly, cb) { + this.sendFrame( + Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x0a, + mask, + readOnly + }), + cb + ); + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const buf = toBuffer(data); + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = buf.length >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + fin: options.fin, + rsv1, + opcode, + mask: options.mask, + readOnly: toBuffer.readOnly + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, this._compress, opts, cb]); + } else { + this.dispatch(buf, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(buf, { + fin: options.fin, + rsv1: false, + opcode, + mask: options.mask, + readOnly: toBuffer.readOnly + }), + cb + ); + } + } + + /** + * Dispatches a data message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += data.length; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const callback = this._queue[i][4]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= data.length; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[1].length; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[1].length; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; diff --git a/node_modules/ws/lib/stream.js b/node_modules/ws/lib/stream.js new file mode 100644 index 0000000..0f85ba5 --- /dev/null +++ b/node_modules/ws/lib/stream.js @@ -0,0 +1,180 @@ +'use strict'; + +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let resumeOnReceiverDrain = true; + let terminateOnDestroy = true; + + function receiverOnDrain() { + if (resumeOnReceiverDrain) ws._socket.resume(); + } + + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + ws._receiver.removeAllListeners('drain'); + ws._receiver.on('drain', receiverOnDrain); + }); + } else { + ws._receiver.removeAllListeners('drain'); + ws._receiver.on('drain', receiverOnDrain); + } + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) { + resumeOnReceiverDrain = false; + ws._socket.pause(); + } + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) { + resumeOnReceiverDrain = true; + if (!ws._receiver._writableState.needDrain) ws._socket.resume(); + } + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/node_modules/ws/lib/subprotocol.js b/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000..d4381e8 --- /dev/null +++ b/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/node_modules/ws/lib/validation.js b/node_modules/ws/lib/validation.js new file mode 100644 index 0000000..ed98c75 --- /dev/null +++ b/node_modules/ws/lib/validation.js @@ -0,0 +1,124 @@ +'use strict'; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports = { + isValidStatusCode, + isValidUTF8(buf) { + return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf); + }, + tokenChars + }; +} catch (e) /* istanbul ignore next */ { + module.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars + }; +} diff --git a/node_modules/ws/lib/websocket-server.js b/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000..3c7939f --- /dev/null +++ b/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,485 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const https = require('https'); +const net = require('net'); +const tls = require('tls'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = + req.headers['sec-websocket-key'] !== undefined + ? req.headers['sec-websocket-key'] + : false; + const version = +req.headers['sec-websocket-version']; + + if ( + req.method !== 'GET' || + req.headers.upgrade.toLowerCase() !== 'websocket' || + !key || + !keyRegex.test(key) || + (version !== 8 && version !== 13) || + !this.shouldHandle(req) + ) { + return abortHandshake(socket, 400); + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + return abortHandshake(socket, 400); + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + return abortHandshake(socket, 400); + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle premature socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + if (socket.writable) { + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.write( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); + } + + socket.removeListener('error', socketOnError); + socket.destroy(); +} diff --git a/node_modules/ws/lib/websocket.js b/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000..818f269 --- /dev/null +++ b/node_modules/ws/lib/websocket.js @@ -0,0 +1,1149 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; +const protocolVersions = [8, 13]; +const closeTimeout = 30 * 1000; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: undefined, + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + websocket._url = address.href; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + + websocket._url = address; + } + + const isSecure = parsedUrl.protocol === 'wss:'; + const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) { + throw new SyntaxError( + 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"' + ); + } + + if (isUnixSocket && !parsedUrl.pathname) { + throw new SyntaxError("The URL's pathname is empty"); + } + + if (parsedUrl.hash) { + throw new SyntaxError('The URL contains a fragment identifier'); + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const get = isSecure ? https.get : http.get; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket', + ...opts.headers + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isUnixSocket) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req = (websocket._req = get(opts)); + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req.aborted) return; + + req = websocket._req = null; + websocket._readyState = WebSocket.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + const addr = new URL(location, address); + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the `upgrade` + // event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + stream.once('abort', websocket.emitClose.bind(websocket)); + websocket.emit('error', err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + cb(err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + this[kWebSocket]._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/node_modules/ws/package.json b/node_modules/ws/package.json new file mode 100644 index 0000000..8afdd2e --- /dev/null +++ b/node_modules/ws/package.json @@ -0,0 +1,61 @@ +{ + "name": "ws", + "version": "8.2.3", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": "websockets/ws", + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^7.2.0", + "eslint-config-prettier": "^8.1.0", + "eslint-plugin-prettier": "^4.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^2.0.5", + "utf-8-validate": "^5.0.2" + } +} diff --git a/node_modules/ws/wrapper.mjs b/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000..7245ad1 --- /dev/null +++ b/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/node_modules/xmlhttprequest-ssl/LICENSE b/node_modules/xmlhttprequest-ssl/LICENSE new file mode 100644 index 0000000..1c63271 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/LICENSE @@ -0,0 +1,22 @@ + Copyright (c) 2010 passive.ly 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/node_modules/xmlhttprequest-ssl/README.md b/node_modules/xmlhttprequest-ssl/README.md new file mode 100644 index 0000000..7e09b94 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/README.md @@ -0,0 +1,67 @@ +# node-XMLHttpRequest # + +Fork of [node-XMLHttpRequest](https://github.com/driverdan/node-XMLHttpRequest) by [driverdan](http://driverdan.com). Forked and published to npm because a [pull request](https://github.com/rase-/node-XMLHttpRequest/commit/a6b6f296e0a8278165c2d0270d9840b54d5eeadd) is not being created and merged. Changes made by [rase-](https://github.com/rase-/node-XMLHttpRequest/tree/add/ssl-support) are needed for [engine.io-client](https://github.com/Automattic/engine.io-client). + +## Usage ## + +Here's how to include the module in your project and use as the browser-based +XHR object. + + var XMLHttpRequest = require("xmlhttprequest-ssl").XMLHttpRequest; + var xhr = new XMLHttpRequest(); + +Note: use the lowercase string "xmlhttprequest-ssl" in your require(). On +case-sensitive systems (eg Linux) using uppercase letters won't work. +# Original README # + +## Usage ## + +Here's how to include the module in your project and use as the browser-based +XHR object. + + var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; + var xhr = new XMLHttpRequest(); + +Note: use the lowercase string "xmlhttprequest" in your require(). On +case-sensitive systems (eg Linux) using uppercase letters won't work. + +## Versions ## + +Version 2.0.0 introduces a potentially breaking change concerning local file system requests. +If these requests fail this library now returns the `errno` (or -1) as the response status code instead of +returning status code 0. + +Prior to 1.4.0 version numbers were arbitrary. From 1.4.0 on they conform to +the standard major.minor.bugfix. 1.x shouldn't necessarily be considered +stable just because it's above 0.x. + +Since the XMLHttpRequest API is stable this library's API is stable as +well. Major version numbers indicate significant core code changes. +Minor versions indicate minor core code changes or better conformity to +the W3C spec. + +## License ## + +MIT license. See LICENSE for full details. + +## Supports ## + +* Async and synchronous requests +* GET, POST, PUT, and DELETE requests +* All spec methods (open, send, abort, getRequestHeader, + getAllRequestHeaders, event methods) +* Requests to all domains + +## Known Issues / Missing Features ## + +For a list of open issues or to report your own visit the [github issues +page](https://github.com/driverdan/node-XMLHttpRequest/issues). + +* Local file access may have unexpected results for non-UTF8 files +* Synchronous requests don't set headers properly +* Synchronous requests freeze node while waiting for response (But that's what you want, right? Stick with async!). +* Some events are missing, such as abort +* getRequestHeader is case-sensitive +* Cookies aren't persisted between requests +* Missing XML support +* Missing basic auth diff --git a/node_modules/xmlhttprequest-ssl/autotest.watchr b/node_modules/xmlhttprequest-ssl/autotest.watchr new file mode 100644 index 0000000..5324db6 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/autotest.watchr @@ -0,0 +1,8 @@ +def run_all_tests + puts `clear` + puts `node tests/test-constants.js` + puts `node tests/test-headers.js` + puts `node tests/test-request.js` +end +watch('.*.js') { run_all_tests } +run_all_tests diff --git a/node_modules/xmlhttprequest-ssl/example/demo.js b/node_modules/xmlhttprequest-ssl/example/demo.js new file mode 100644 index 0000000..1872ab5 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/example/demo.js @@ -0,0 +1,16 @@ +var sys = require('util'); +var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; + +var xhr = new XMLHttpRequest(); + +xhr.onreadystatechange = function() { + console.log("State: " + this.readyState); + + if (this.readyState == 4) { + console.log("Complete.\nBody length: " + this.responseText.length); + console.log("Body:\n" + this.responseText); + } +}; + +xhr.open("GET", "http://driverdan.com"); +xhr.send(); diff --git a/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js b/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js new file mode 100644 index 0000000..c0da822 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js @@ -0,0 +1,673 @@ +/** + * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object. + * + * This can be used with JS designed for browsers to improve reuse of code and + * allow the use of existing libraries. + * + * Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs. + * + * @author Dan DeFelippi + * @contributor David Ellis + * @license MIT + */ + +var fs = require('fs'); +var Url = require('url'); +var spawn = require('child_process').spawn; + +/** + * Module exports. + */ + +module.exports = XMLHttpRequest; + +// backwards-compat +XMLHttpRequest.XMLHttpRequest = XMLHttpRequest; + +/** + * `XMLHttpRequest` constructor. + * + * Supported options for the `opts` object are: + * + * - `agent`: An http.Agent instance; http.globalAgent may be used; if 'undefined', agent usage is disabled + * + * @param {Object} opts optional "options" object + */ + +function XMLHttpRequest(opts) { + "use strict"; + + opts = opts || {}; + + /** + * Private variables + */ + var self = this; + var http = require('http'); + var https = require('https'); + + // Holds http.js objects + var request; + var response; + + // Request settings + var settings = {}; + + // Disable header blacklist. + // Not part of XHR specs. + var disableHeaderCheck = false; + + // Set some default headers + var defaultHeaders = { + "User-Agent": "node-XMLHttpRequest", + "Accept": "*/*" + }; + + var headers = Object.assign({}, defaultHeaders); + + // These headers are not user setable. + // The following are allowed but banned in the spec: + // * user-agent + var forbiddenRequestHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "content-transfer-encoding", + "cookie", + "cookie2", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]; + + // These request methods are not allowed + var forbiddenRequestMethods = [ + "TRACE", + "TRACK", + "CONNECT" + ]; + + // Send flag + var sendFlag = false; + // Error flag, used when errors occur or abort is called + var errorFlag = false; + var abortedFlag = false; + + // Event listeners + var listeners = {}; + + /** + * Constants + */ + + this.UNSENT = 0; + this.OPENED = 1; + this.HEADERS_RECEIVED = 2; + this.LOADING = 3; + this.DONE = 4; + + /** + * Public vars + */ + + // Current state + this.readyState = this.UNSENT; + + // default ready state change handler in case one is not set or is set late + this.onreadystatechange = null; + + // Result & response + this.responseText = ""; + this.responseXML = ""; + this.status = null; + this.statusText = null; + + /** + * Private methods + */ + + /** + * Check if the specified header is allowed. + * + * @param string header Header to validate + * @return boolean False if not allowed, otherwise true + */ + var isAllowedHttpHeader = function(header) { + return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1); + }; + + /** + * Check if the specified method is allowed. + * + * @param string method Request method to validate + * @return boolean False if not allowed, otherwise true + */ + var isAllowedHttpMethod = function(method) { + return (method && forbiddenRequestMethods.indexOf(method) === -1); + }; + + /** + * Public methods + */ + + /** + * Open the connection. Currently supports local server requests. + * + * @param string method Connection method (eg GET, POST) + * @param string url URL for the connection. + * @param boolean async Asynchronous connection. Default is true. + * @param string user Username for basic authentication (optional) + * @param string password Password for basic authentication (optional) + */ + this.open = function(method, url, async, user, password) { + this.abort(); + errorFlag = false; + abortedFlag = false; + + // Check for valid request method + if (!isAllowedHttpMethod(method)) { + throw new Error("SecurityError: Request method not allowed"); + } + + settings = { + "method": method, + "url": url.toString(), + "async": (typeof async !== "boolean" ? true : async), + "user": user || null, + "password": password || null + }; + + setState(this.OPENED); + }; + + /** + * Disables or enables isAllowedHttpHeader() check the request. Enabled by default. + * This does not conform to the W3C spec. + * + * @param boolean state Enable or disable header checking. + */ + this.setDisableHeaderCheck = function(state) { + disableHeaderCheck = state; + }; + + /** + * Sets a header for the request. + * + * @param string header Header name + * @param string value Header value + * @return boolean Header added + */ + this.setRequestHeader = function(header, value) { + if (this.readyState != this.OPENED) { + throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN"); + } + if (!isAllowedHttpHeader(header)) { + console.warn('Refused to set unsafe header "' + header + '"'); + return false; + } + if (sendFlag) { + throw new Error("INVALID_STATE_ERR: send flag is true"); + } + headers[header] = value; + return true; + }; + + /** + * Gets a header from the server response. + * + * @param string header Name of header to get. + * @return string Text of the header or null if it doesn't exist. + */ + this.getResponseHeader = function(header) { + if (typeof header === "string" + && this.readyState > this.OPENED + && response.headers[header.toLowerCase()] + && !errorFlag + ) { + return response.headers[header.toLowerCase()]; + } + + return null; + }; + + /** + * Gets all the response headers. + * + * @return string A string with all response headers separated by CR+LF + */ + this.getAllResponseHeaders = function() { + if (this.readyState < this.HEADERS_RECEIVED || errorFlag) { + return ""; + } + var result = ""; + + for (var i in response.headers) { + // Cookie headers are excluded + if (i !== "set-cookie" && i !== "set-cookie2") { + result += i + ": " + response.headers[i] + "\r\n"; + } + } + return result.substr(0, result.length - 2); + }; + + /** + * Gets a request header + * + * @param string name Name of header to get + * @return string Returns the request header or empty string if not set + */ + this.getRequestHeader = function(name) { + // @TODO Make this case insensitive + if (typeof name === "string" && headers[name]) { + return headers[name]; + } + + return ""; + }; + + /** + * Sends the request to the server. + * + * @param string data Optional data to send as request body. + */ + this.send = function(data) { + if (this.readyState != this.OPENED) { + throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called"); + } + + if (sendFlag) { + throw new Error("INVALID_STATE_ERR: send has already been called"); + } + + var ssl = false, local = false; + var url = Url.parse(settings.url); + var host; + // Determine the server + switch (url.protocol) { + case 'https:': + ssl = true; + // SSL & non-SSL both need host, no break here. + case 'http:': + host = url.hostname; + break; + + case 'file:': + local = true; + break; + + case undefined: + case '': + host = "localhost"; + break; + + default: + throw new Error("Protocol not supported."); + } + + // Load files off the local filesystem (file://) + if (local) { + if (settings.method !== "GET") { + throw new Error("XMLHttpRequest: Only GET method is supported"); + } + + if (settings.async) { + fs.readFile(unescape(url.pathname), 'utf8', function(error, data) { + if (error) { + self.handleError(error, error.errno || -1); + } else { + self.status = 200; + self.responseText = data; + setState(self.DONE); + } + }); + } else { + try { + this.responseText = fs.readFileSync(unescape(url.pathname), 'utf8'); + this.status = 200; + setState(self.DONE); + } catch(e) { + this.handleError(e, e.errno || -1); + } + } + + return; + } + + // Default to port 80. If accessing localhost on another port be sure + // to use http://localhost:port/path + var port = url.port || (ssl ? 443 : 80); + // Add query string if one is used + var uri = url.pathname + (url.search ? url.search : ''); + + // Set the Host header or the server may reject the request + headers["Host"] = host; + if (!((ssl && port === 443) || port === 80)) { + headers["Host"] += ':' + url.port; + } + + // Set Basic Auth if necessary + if (settings.user) { + if (typeof settings.password == "undefined") { + settings.password = ""; + } + var authBuf = new Buffer(settings.user + ":" + settings.password); + headers["Authorization"] = "Basic " + authBuf.toString("base64"); + } + + // Set content length header + if (settings.method === "GET" || settings.method === "HEAD") { + data = null; + } else if (data) { + headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data); + + if (!headers["Content-Type"]) { + headers["Content-Type"] = "text/plain;charset=UTF-8"; + } + } else if (settings.method === "POST") { + // For a post with no data set Content-Length: 0. + // This is required by buggy servers that don't meet the specs. + headers["Content-Length"] = 0; + } + + var agent = opts.agent || false; + var options = { + host: host, + port: port, + path: uri, + method: settings.method, + headers: headers, + agent: agent + }; + + if (ssl) { + options.pfx = opts.pfx; + options.key = opts.key; + options.passphrase = opts.passphrase; + options.cert = opts.cert; + options.ca = opts.ca; + options.ciphers = opts.ciphers; + options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true; + } + + // Reset error flag + errorFlag = false; + // Handle async requests + if (settings.async) { + // Use the proper protocol + var doRequest = ssl ? https.request : http.request; + + // Request is being sent, set send flag + sendFlag = true; + + // As per spec, this is called here for historical reasons. + self.dispatchEvent("readystatechange"); + + // Handler for the response + var responseHandler = function(resp) { + // Set response var to the response we got back + // This is so it remains accessable outside this scope + response = resp; + // Check for redirect + // @TODO Prevent looped redirects + if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { + // Change URL to the redirect location + settings.url = response.headers.location; + var url = Url.parse(settings.url); + // Set host var in case it's used later + host = url.hostname; + // Options for the new request + var newOptions = { + hostname: url.hostname, + port: url.port, + path: url.path, + method: response.statusCode === 303 ? 'GET' : settings.method, + headers: headers + }; + + if (ssl) { + newOptions.pfx = opts.pfx; + newOptions.key = opts.key; + newOptions.passphrase = opts.passphrase; + newOptions.cert = opts.cert; + newOptions.ca = opts.ca; + newOptions.ciphers = opts.ciphers; + newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true; + } + + // Issue the new request + request = doRequest(newOptions, responseHandler).on('error', errorHandler); + request.end(); + // @TODO Check if an XHR event needs to be fired here + return; + } + + if (response && response.setEncoding) { + response.setEncoding("utf8"); + } + + setState(self.HEADERS_RECEIVED); + self.status = response.statusCode; + + response.on('data', function(chunk) { + // Make sure there's some data + if (chunk) { + self.responseText += chunk; + } + // Don't emit state changes if the connection has been aborted. + if (sendFlag) { + setState(self.LOADING); + } + }); + + response.on('end', function() { + if (sendFlag) { + // The sendFlag needs to be set before setState is called. Otherwise if we are chaining callbacks + // there can be a timing issue (the callback is called and a new call is made before the flag is reset). + sendFlag = false; + // Discard the 'end' event if the connection has been aborted + setState(self.DONE); + } + }); + + response.on('error', function(error) { + self.handleError(error); + }); + } + + // Error handler for the request + var errorHandler = function(error) { + self.handleError(error); + } + + // Create the request + request = doRequest(options, responseHandler).on('error', errorHandler); + + if (opts.autoUnref) { + request.on('socket', (socket) => { + socket.unref(); + }); + } + + // Node 0.4 and later won't accept empty data. Make sure it's needed. + if (data) { + request.write(data); + } + + request.end(); + + self.dispatchEvent("loadstart"); + } else { // Synchronous + // Create a temporary file for communication with the other Node process + var contentFile = ".node-xmlhttprequest-content-" + process.pid; + var syncFile = ".node-xmlhttprequest-sync-" + process.pid; + fs.writeFileSync(syncFile, "", "utf8"); + // The async request the other Node process executes + var execString = "var http = require('http'), https = require('https'), fs = require('fs');" + + "var doRequest = http" + (ssl ? "s" : "") + ".request;" + + "var options = " + JSON.stringify(options) + ";" + + "var responseText = '';" + + "var req = doRequest(options, function(response) {" + + "response.setEncoding('utf8');" + + "response.on('data', function(chunk) {" + + " responseText += chunk;" + + "});" + + "response.on('end', function() {" + + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');" + + "fs.unlinkSync('" + syncFile + "');" + + "});" + + "response.on('error', function(error) {" + + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');" + + "fs.unlinkSync('" + syncFile + "');" + + "});" + + "}).on('error', function(error) {" + + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');" + + "fs.unlinkSync('" + syncFile + "');" + + "});" + + (data ? "req.write('" + JSON.stringify(data).slice(1,-1).replace(/'/g, "\\'") + "');":"") + + "req.end();"; + // Start the other Node Process, executing this string + var syncProc = spawn(process.argv[0], ["-e", execString]); + var statusText; + while(fs.existsSync(syncFile)) { + // Wait while the sync file is empty + } + self.responseText = fs.readFileSync(contentFile, 'utf8'); + // Kill the child process once the file has data + syncProc.stdin.end(); + // Remove the temporary file + fs.unlinkSync(contentFile); + if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) { + // If the file returned an error, handle it + var errorObj = self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, ""); + self.handleError(errorObj, 503); + } else { + // If the file returned okay, parse its data and move to the DONE state + self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1"); + self.responseText = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1"); + setState(self.DONE); + } + } + }; + + /** + * Called when an error is encountered to deal with it. + * @param status {number} HTTP status code to use rather than the default (0) for XHR errors. + */ + this.handleError = function(error, status) { + this.status = status || 0; + this.statusText = error; + this.responseText = error.stack; + errorFlag = true; + setState(this.DONE); + }; + + /** + * Aborts a request. + */ + this.abort = function() { + if (request) { + request.abort(); + request = null; + } + + headers = Object.assign({}, defaultHeaders); + this.responseText = ""; + this.responseXML = ""; + + errorFlag = abortedFlag = true + if (this.readyState !== this.UNSENT + && (this.readyState !== this.OPENED || sendFlag) + && this.readyState !== this.DONE) { + sendFlag = false; + setState(this.DONE); + } + this.readyState = this.UNSENT; + }; + + /** + * Adds an event listener. Preferred method of binding to events. + */ + this.addEventListener = function(event, callback) { + if (!(event in listeners)) { + listeners[event] = []; + } + // Currently allows duplicate callbacks. Should it? + listeners[event].push(callback); + }; + + /** + * Remove an event callback that has already been bound. + * Only works on the matching funciton, cannot be a copy. + */ + this.removeEventListener = function(event, callback) { + if (event in listeners) { + // Filter will return a new array with the callback removed + listeners[event] = listeners[event].filter(function(ev) { + return ev !== callback; + }); + } + }; + + /** + * Dispatch any events, including both "on" methods and events attached using addEventListener. + */ + this.dispatchEvent = function(event) { + if (typeof self["on" + event] === "function") { + if (this.readyState === this.DONE) + setImmediate(function() { self["on" + event]() }) + else + self["on" + event]() + } + if (event in listeners) { + for (let i = 0, len = listeners[event].length; i < len; i++) { + if (this.readyState === this.DONE) + setImmediate(function() { listeners[event][i].call(self) }) + else + listeners[event][i].call(self) + } + } + }; + + /** + * Changes readyState and calls onreadystatechange. + * + * @param int state New state + */ + var setState = function(state) { + if ((self.readyState === state) || (self.readyState === self.UNSENT && abortedFlag)) + return + + self.readyState = state; + + if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) { + self.dispatchEvent("readystatechange"); + } + + if (self.readyState === self.DONE) { + let fire + + if (abortedFlag) + fire = "abort" + else if (errorFlag) + fire = "error" + else + fire = "load" + + self.dispatchEvent(fire) + + // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie) + self.dispatchEvent("loadend"); + } + }; +}; diff --git a/node_modules/xmlhttprequest-ssl/package.json b/node_modules/xmlhttprequest-ssl/package.json new file mode 100644 index 0000000..ba87b85 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/package.json @@ -0,0 +1,35 @@ +{ + "name": "xmlhttprequest-ssl", + "description": "XMLHttpRequest for Node", + "version": "2.0.0", + "author": { + "name": "Michael de Wit" + }, + "keywords": [ + "xhr", + "ajax" + ], + "licenses": [ + { + "type": "MIT", + "url": "http://creativecommons.org/licenses/MIT/" + } + ], + "repository": { + "type": "git", + "url": "git://github.com/mjwwit/node-XMLHttpRequest.git" + }, + "bugs": "http://github.com/mjwwit/node-XMLHttpRequest/issues", + "engines": { + "node": ">=0.4.0" + }, + "scripts": { + "test": "cd ./tests && node test-constants.js && node test-events.js && node test-exceptions.js && node test-headers.js && node test-redirect-302.js && node test-redirect-303.js && node test-redirect-307.js && node test-request-methods.js && node test-request-protocols.js" + }, + "directories": { + "lib": "./lib", + "example": "./example" + }, + "main": "./lib/XMLHttpRequest.js", + "dependencies": {} +} diff --git a/node_modules/xmlhttprequest-ssl/tests/test-constants.js b/node_modules/xmlhttprequest-ssl/tests/test-constants.js new file mode 100644 index 0000000..4c697e2 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-constants.js @@ -0,0 +1,13 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest(); + +// Test constant values +assert.equal(0, xhr.UNSENT); +assert.equal(1, xhr.OPENED); +assert.equal(2, xhr.HEADERS_RECEIVED); +assert.equal(3, xhr.LOADING); +assert.equal(4, xhr.DONE); + +console.log("done"); diff --git a/node_modules/xmlhttprequest-ssl/tests/test-events.js b/node_modules/xmlhttprequest-ssl/tests/test-events.js new file mode 100644 index 0000000..3296f8b --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-events.js @@ -0,0 +1,50 @@ +var sys = require("util") + , assert = require("assert") + , http = require("http") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr; + +// Test server +var server = http.createServer(function (req, res) { + var body = (req.method != "HEAD" ? "Hello World" : ""); + + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body) + }); + // HEAD has no body + if (req.method != "HEAD") { + res.write(body); + } + res.end(); + assert.equal(onreadystatechange, true); + assert.equal(readystatechange, true); + assert.equal(removed, true); + console.log("done"); + this.close(); +}).listen(8000); + +xhr = new XMLHttpRequest(); + +// Track event calls +var onreadystatechange = false; +var readystatechange = false; +var removed = true; +var removedEvent = function() { + removed = false; +}; + +xhr.onreadystatechange = function() { + onreadystatechange = true; +}; + +xhr.addEventListener("readystatechange", function() { + readystatechange = true; +}); + +// This isn't perfect, won't guarantee it was added in the first place +xhr.addEventListener("readystatechange", removedEvent); +xhr.removeEventListener("readystatechange", removedEvent); + +xhr.open("GET", "http://localhost:8000"); +xhr.send(); diff --git a/node_modules/xmlhttprequest-ssl/tests/test-exceptions.js b/node_modules/xmlhttprequest-ssl/tests/test-exceptions.js new file mode 100644 index 0000000..10eaea2 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-exceptions.js @@ -0,0 +1,59 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest(); + +// Test request methods that aren't allowed +try { + xhr.open("TRACK", "http://localhost:8000/"); + console.log("ERROR: TRACK should have thrown exception"); +} catch(e) {} +try { + xhr.open("TRACE", "http://localhost:8000/"); + console.log("ERROR: TRACE should have thrown exception"); +} catch(e) {} +try { + xhr.open("CONNECT", "http://localhost:8000/"); + console.log("ERROR: CONNECT should have thrown exception"); +} catch(e) {} +// Test valid request method +try { + xhr.open("GET", "http://localhost:8000/"); +} catch(e) { + console.log("ERROR: Invalid exception for GET", e); +} + +// Test forbidden headers +var forbiddenRequestHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "content-transfer-encoding", + "cookie", + "cookie2", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" +]; + +for (var i in forbiddenRequestHeaders) { + if(xhr.setRequestHeader(forbiddenRequestHeaders[i], "Test") !== false) { + console.log("ERROR: " + forbiddenRequestHeaders[i] + " should have thrown exception"); + } +} + +// Try valid header +xhr.setRequestHeader("X-Foobar", "Test"); + +console.log("Done"); diff --git a/node_modules/xmlhttprequest-ssl/tests/test-headers.js b/node_modules/xmlhttprequest-ssl/tests/test-headers.js new file mode 100644 index 0000000..27ecc25 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-headers.js @@ -0,0 +1,76 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest() + , http = require("http"); + +// Test server +var server = http.createServer(function (req, res) { + // Test setRequestHeader + assert.equal("Foobar", req.headers["x-test"]); + // Test non-conforming allowed header + assert.equal("node-XMLHttpRequest-test", req.headers["user-agent"]); + // Test header set with blacklist disabled + assert.equal("http://github.com", req.headers["referer"]); + + var body = "Hello World"; + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body), + // Set cookie headers to see if they're correctly suppressed + // Actual values don't matter + "Set-Cookie": "foo=bar", + "Set-Cookie2": "bar=baz", + "Date": "Thu, 30 Aug 2012 18:17:53 GMT", + "Connection": "close" + }); + res.write("Hello World"); + res.end(); + + this.close(); +}).listen(8000); + +xhr.onreadystatechange = function() { + if (this.readyState == 4) { + // Test getAllResponseHeaders() + var headers = "content-type: text/plain\r\ncontent-length: 11\r\ndate: Thu, 30 Aug 2012 18:17:53 GMT\r\nconnection: close"; + assert.equal(headers, this.getAllResponseHeaders()); + + // Test case insensitivity + assert.equal('text/plain', this.getResponseHeader('Content-Type')); + assert.equal('text/plain', this.getResponseHeader('Content-type')); + assert.equal('text/plain', this.getResponseHeader('content-Type')); + assert.equal('text/plain', this.getResponseHeader('content-type')); + + // Test aborted getAllResponseHeaders + this.abort(); + assert.equal("", this.getAllResponseHeaders()); + assert.equal(null, this.getResponseHeader("Connection")); + + console.log("done"); + } +}; + +assert.equal(null, xhr.getResponseHeader("Content-Type")); +try { + xhr.open("GET", "http://localhost:8000/"); + // Valid header + xhr.setRequestHeader("X-Test", "Foobar"); + // Invalid header + xhr.setRequestHeader("Content-Length", 0); + // Allowed header outside of specs + xhr.setRequestHeader("user-agent", "node-XMLHttpRequest-test"); + // Test getRequestHeader + assert.equal("Foobar", xhr.getRequestHeader("X-Test")); + // Test invalid header + assert.equal("", xhr.getRequestHeader("Content-Length")); + + // Test allowing all headers + xhr.setDisableHeaderCheck(true); + xhr.setRequestHeader("Referer", "http://github.com"); + assert.equal("http://github.com", xhr.getRequestHeader("Referer")); + + xhr.send(); +} catch(e) { + console.log("ERROR: Exception raised", e); +} diff --git a/node_modules/xmlhttprequest-ssl/tests/test-redirect-302.js b/node_modules/xmlhttprequest-ssl/tests/test-redirect-302.js new file mode 100644 index 0000000..0b87192 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-redirect-302.js @@ -0,0 +1,41 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest() + , http = require("http"); + +// Test server +var server = http.createServer(function (req, res) { + if (req.url === '/redirectingResource') { + res.writeHead(302, {'Location': 'http://localhost:8000/'}); + res.end(); + return; + } + + var body = "Hello World"; + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body), + "Date": "Thu, 30 Aug 2012 18:17:53 GMT", + "Connection": "close" + }); + res.write("Hello World"); + res.end(); + + this.close(); +}).listen(8000); + +xhr.onreadystatechange = function() { + if (this.readyState == 4) { + assert.equal(xhr.getRequestHeader('Location'), ''); + assert.equal(xhr.responseText, "Hello World"); + console.log("done"); + } +}; + +try { + xhr.open("GET", "http://localhost:8000/redirectingResource"); + xhr.send(); +} catch(e) { + console.log("ERROR: Exception raised", e); +} diff --git a/node_modules/xmlhttprequest-ssl/tests/test-redirect-303.js b/node_modules/xmlhttprequest-ssl/tests/test-redirect-303.js new file mode 100644 index 0000000..aa85b2d --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-redirect-303.js @@ -0,0 +1,41 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest() + , http = require("http"); + +// Test server +var server = http.createServer(function (req, res) { + if (req.url === '/redirectingResource') { + res.writeHead(303, {'Location': 'http://localhost:8000/'}); + res.end(); + return; + } + + var body = "Hello World"; + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body), + "Date": "Thu, 30 Aug 2012 18:17:53 GMT", + "Connection": "close" + }); + res.write("Hello World"); + res.end(); + + this.close(); +}).listen(8000); + +xhr.onreadystatechange = function() { + if (this.readyState == 4) { + assert.equal(xhr.getRequestHeader('Location'), ''); + assert.equal(xhr.responseText, "Hello World"); + console.log("done"); + } +}; + +try { + xhr.open("POST", "http://localhost:8000/redirectingResource"); + xhr.send(); +} catch(e) { + console.log("ERROR: Exception raised", e); +} diff --git a/node_modules/xmlhttprequest-ssl/tests/test-redirect-307.js b/node_modules/xmlhttprequest-ssl/tests/test-redirect-307.js new file mode 100644 index 0000000..a73819f --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-redirect-307.js @@ -0,0 +1,43 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr = new XMLHttpRequest() + , http = require("http"); + +// Test server +var server = http.createServer(function (req, res) { + if (req.url === '/redirectingResource') { + res.writeHead(307, {'Location': 'http://localhost:8000/'}); + res.end(); + return; + } + + assert.equal(req.method, 'POST'); + + var body = "Hello World"; + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body), + "Date": "Thu, 30 Aug 2012 18:17:53 GMT", + "Connection": "close" + }); + res.write("Hello World"); + res.end(); + + this.close(); +}).listen(8000); + +xhr.onreadystatechange = function() { + if (this.readyState == 4) { + assert.equal(xhr.getRequestHeader('Location'), ''); + assert.equal(xhr.responseText, "Hello World"); + console.log("done"); + } +}; + +try { + xhr.open("POST", "http://localhost:8000/redirectingResource"); + xhr.send(); +} catch(e) { + console.log("ERROR: Exception raised", e); +} diff --git a/node_modules/xmlhttprequest-ssl/tests/test-request-methods.js b/node_modules/xmlhttprequest-ssl/tests/test-request-methods.js new file mode 100644 index 0000000..f8d66d8 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-request-methods.js @@ -0,0 +1,62 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , http = require("http") + , xhr; + +// Test server +var server = http.createServer(function (req, res) { + // Check request method and URL + assert.equal(methods[curMethod], req.method); + assert.equal("/" + methods[curMethod], req.url); + + var body = (req.method != "HEAD" ? "Hello World" : ""); + + res.writeHead(200, { + "Content-Type": "text/plain", + "Content-Length": Buffer.byteLength(body) + }); + // HEAD has no body + if (req.method != "HEAD") { + res.write(body); + } + res.end(); + + if (curMethod == methods.length - 1) { + this.close(); + console.log("done"); + } +}).listen(8000); + +// Test standard methods +var methods = ["GET", "POST", "HEAD", "PUT", "DELETE"]; +var curMethod = 0; + +function start(method) { + // Reset each time + xhr = new XMLHttpRequest(); + + xhr.onreadystatechange = function() { + if (this.readyState == 4) { + if (method == "HEAD") { + assert.equal("", this.responseText); + } else { + assert.equal("Hello World", this.responseText); + } + + curMethod++; + + if (curMethod < methods.length) { + console.log("Testing " + methods[curMethod]); + start(methods[curMethod]); + } + } + }; + + var url = "http://localhost:8000/" + method; + xhr.open(method, url); + xhr.send(); +} + +console.log("Testing " + methods[curMethod]); +start(methods[curMethod]); diff --git a/node_modules/xmlhttprequest-ssl/tests/test-request-protocols.js b/node_modules/xmlhttprequest-ssl/tests/test-request-protocols.js new file mode 100644 index 0000000..f745cb8 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/test-request-protocols.js @@ -0,0 +1,32 @@ +var sys = require("util") + , assert = require("assert") + , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest + , xhr; + +xhr = new XMLHttpRequest(); + +xhr.onreadystatechange = function() { + if (this.readyState == 4) { + assert.equal("Hello World", this.responseText); + runSync(); + } +}; + +// Async +var url = "file://" + __dirname + "/testdata.txt"; +xhr.open("GET", url); +xhr.send(); + +// Sync +var runSync = function() { + xhr = new XMLHttpRequest(); + + xhr.onreadystatechange = function() { + if (this.readyState == 4) { + assert.equal("Hello World", this.responseText); + console.log("done"); + } + }; + xhr.open("GET", url, false); + xhr.send(); +} diff --git a/node_modules/xmlhttprequest-ssl/tests/testdata.txt b/node_modules/xmlhttprequest-ssl/tests/testdata.txt new file mode 100644 index 0000000..5e1c309 --- /dev/null +++ b/node_modules/xmlhttprequest-ssl/tests/testdata.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9f8bac3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,363 @@ +{ + "name": "nodejs", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "nodejs", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@types/node": "^18.0.6", + "dotenv": "^16.0.1", + "node-fetch": "^3.2.6", + "pathfinding": "^0.4.18", + "socket.io-client": "^4.5.1" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", + "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" + }, + "node_modules/@types/node": { + "version": "18.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.5.tgz", + "integrity": "sha512-NcKK6Ts+9LqdHJaW6HQmgr7dT/i3GOHG+pt6BiWv++5SnjtRd4NXeiuN2kA153SjhXPR/AhHIPHPbrsbpUVOww==" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz", + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dotenv": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.1.tgz", + "integrity": "sha512-1K6hR6wtk2FviQ4kEiSjFiH5rpzEVi8WW0x96aztHVMhEspNpc4DVOUTEHtEva5VThQ8IaBX1Pe4gSzpVVUsKQ==", + "engines": { + "node": ">=12" + } + }, + "node_modules/engine.io-client": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.2.2.tgz", + "integrity": "sha512-8ZQmx0LQGRTYkHuogVZuGSpDqYZtCM/nv8zQ68VZ+JkOpazJ7ICdsSpaO6iXwvaU30oFg5QJOJWj8zWqhbKjkQ==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3", + "xmlhttprequest-ssl": "~2.0.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.4.tgz", + "integrity": "sha512-+nVFp+5z1E3HcToEnO7ZIj3g+3k9389DvWtvJZz0T6/eOCPIyyxehFcedoYrZQrp0LgQbD9pPXhpMBKMd5QURg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/heap": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/heap/-/heap-0.2.5.tgz", + "integrity": "sha512-G7HLD+WKcrOyJP5VQwYZNC3Z6FcQ7YYjEFiFoIj8PfEr73mu421o8B1N5DKUcc8K37EsJ2XXWA8DtrDz/2dReg==" + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.2.10", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.10.tgz", + "integrity": "sha512-MhuzNwdURnZ1Cp4XTazr69K0BTizsBroX7Zx3UgDSVcZYKF/6p0CBe4EUb/hLqmzVhl0UpYfgRljQ4yxE+iCxA==", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/pathfinding": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/pathfinding/-/pathfinding-0.4.18.tgz", + "integrity": "sha512-R0TGEQ9GRcFCDvAWlJAWC+KGJ9SLbW4c0nuZRcioVlXVTlw+F5RvXQ8SQgSqI9KXWC1ew95vgmIiyaWTlCe9Ag==", + "dependencies": { + "heap": "0.2.5" + } + }, + "node_modules/socket.io-client": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.5.1.tgz", + "integrity": "sha512-e6nLVgiRYatS+AHXnOnGi4ocOpubvOUCGhyWw8v+/FxW8saHkinG6Dfhi9TU0Kt/8mwJIAASxvw6eujQmjdZVA==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.2.1", + "socket.io-parser": "~4.2.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.1.tgz", + "integrity": "sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", + "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==", + "engines": { + "node": ">=0.4.0" + } + } + }, + "dependencies": { + "@socket.io/component-emitter": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", + "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" + }, + "@types/node": { + "version": "18.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.5.tgz", + "integrity": "sha512-NcKK6Ts+9LqdHJaW6HQmgr7dT/i3GOHG+pt6BiWv++5SnjtRd4NXeiuN2kA153SjhXPR/AhHIPHPbrsbpUVOww==" + }, + "data-uri-to-buffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz", + "integrity": "sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==" + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "requires": { + "ms": "2.1.2" + } + }, + "dotenv": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.1.tgz", + "integrity": "sha512-1K6hR6wtk2FviQ4kEiSjFiH5rpzEVi8WW0x96aztHVMhEspNpc4DVOUTEHtEva5VThQ8IaBX1Pe4gSzpVVUsKQ==" + }, + "engine.io-client": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.2.2.tgz", + "integrity": "sha512-8ZQmx0LQGRTYkHuogVZuGSpDqYZtCM/nv8zQ68VZ+JkOpazJ7ICdsSpaO6iXwvaU30oFg5QJOJWj8zWqhbKjkQ==", + "requires": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3", + "xmlhttprequest-ssl": "~2.0.0" + } + }, + "engine.io-parser": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.4.tgz", + "integrity": "sha512-+nVFp+5z1E3HcToEnO7ZIj3g+3k9389DvWtvJZz0T6/eOCPIyyxehFcedoYrZQrp0LgQbD9pPXhpMBKMd5QURg==" + }, + "fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "requires": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + } + }, + "formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "requires": { + "fetch-blob": "^3.1.2" + } + }, + "heap": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/heap/-/heap-0.2.5.tgz", + "integrity": "sha512-G7HLD+WKcrOyJP5VQwYZNC3Z6FcQ7YYjEFiFoIj8PfEr73mu421o8B1N5DKUcc8K37EsJ2XXWA8DtrDz/2dReg==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==" + }, + "node-fetch": { + "version": "3.2.10", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.2.10.tgz", + "integrity": "sha512-MhuzNwdURnZ1Cp4XTazr69K0BTizsBroX7Zx3UgDSVcZYKF/6p0CBe4EUb/hLqmzVhl0UpYfgRljQ4yxE+iCxA==", + "requires": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + } + }, + "pathfinding": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/pathfinding/-/pathfinding-0.4.18.tgz", + "integrity": "sha512-R0TGEQ9GRcFCDvAWlJAWC+KGJ9SLbW4c0nuZRcioVlXVTlw+F5RvXQ8SQgSqI9KXWC1ew95vgmIiyaWTlCe9Ag==", + "requires": { + "heap": "0.2.5" + } + }, + "socket.io-client": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.5.1.tgz", + "integrity": "sha512-e6nLVgiRYatS+AHXnOnGi4ocOpubvOUCGhyWw8v+/FxW8saHkinG6Dfhi9TU0Kt/8mwJIAASxvw6eujQmjdZVA==", + "requires": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.2.1", + "socket.io-parser": "~4.2.0" + } + }, + "socket.io-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.1.tgz", + "integrity": "sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g==", + "requires": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + } + }, + "web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==" + }, + "ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "requires": {} + }, + "xmlhttprequest-ssl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", + "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2b0767d --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "nodejs", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "@types/node": "^18.0.6", + "dotenv": "^16.0.1", + "node-fetch": "^3.2.6", + "pathfinding": "^0.4.18", + "socket.io-client": "^4.5.1" + } +} diff --git a/wrapper.js b/wrapper.js new file mode 100644 index 0000000..f391898 --- /dev/null +++ b/wrapper.js @@ -0,0 +1,195 @@ +// This is what connects your code to the server, and the code that provides extra utilities. Edit with caution. + +const { io } = require("socket.io-client"); + +function distanceBetweenPoints(p1, p2) { + return Math.abs(Math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]))); +} + +module.exports = function(auth, host = "https://Code-your-snake.codingmaster398.repl.co"){ + const socket = io(host, { + extraHeaders: { + "cookie": `REPL_AUTH=${auth}` + } + }); + + this.username = `` + this.onLogin = ()=>{} + this.onSpawnFail = this.spawn + this.onSpawn = ()=>{} + this.onAnnouncement = ()=>{} + this.onDeath = ()=>{} + this.onKill = ()=>{} + this.onTick = ()=>{} + this.spawned = false + this.x = 0 + this.y = 0 + + this.spawn = ()=>{ + socket.emit('spawn') + } + + this.disconnect = ()=>{ + socket.disconnect() + } + + this.setDirection = (d)=>{ + if(typeof d == 'string'){ + d = d.toLowerCase() + + if(d.startsWith('l')){ + d = 0 + }else if(d.startsWith('r')){ + d = 1 + }else if(d.startsWith('u')){ + d = 2 + }else if(d.startsWith('d')){ + d = 3 + } + } + socket.emit('direction',d) + } + + this.me = ()=>{ + if(this.spawned && this.objects.players[this.username]){ + return this.objects.players[this.username] + }else return; + } + + this.closestApple = ()=>{ + if(this.objects.players[this.username]){ + + let apples = this.apples() + let closest = [0,0] + let closestnum = 999 + for(let e=0; e{ + if(this.objects.players[this.username]){ + + let apples = [] + + for(let i=0;i{ + if(this.objects.players[this.username]){ + + let bhs = [] + + for(let i=0;i{ + if(this.objects.players[this.username]){ + + let bp = [] + + for (const player in this.objects.players) { + for(let i=0;i{ + if(this.objects.players[this.username]){ + + let bp = [] + + for (const player in this.objects.players) { + bp.push(this.objects.players[player].head) + } + + return bp + }else{return []} + } + this.partPositions = ()=>{ + if(this.objects.players[this.username]){ + return [...this.headPositions(), ...this.bodyPositions()] + }else{return[]} + } + + this.objects = { + players:{}, + other:[] + } + + socket.on('loggedIn',(a,b)=>{ + if(a){ + this.onLogin(b) + this.username = b + }else{ + throw "Authentication is wrong - please check what you pass to the starting function" + } + }) + + socket.on('spawned',(d)=>{ + if(d[0]){ + this.onSpawn(d[1],d[2]) + this.spawned = true + }else{ + this.onSpawnFail() + this.spawned = false + } + }) + + socket.on('message',(a)=>{ + this.onAnnouncement(a) + }) + + socket.on('death',(reason)=>{ + this.spawned = false + this.onDeath(reason) + }) + + socket.on('kill',(a)=>{ + this.onKill(a[0],a[1]) + }) + + socket.on('objects',(o)=>{ + this.objects = o + if(this.objects.players[this.username]){ + + this.x = this.objects.players[this.username].head[0] + this.y = this.objects.players[this.username].head[1] + + } + this.onTick(o) + }) + + socket.on('disconnect',()=>{ + this.spawned = false + socket.connect() + }) + + return this +}